Add a new ViewModel file into the ViewModel folder and name it as PostListViewModel.cs. It should inherit from the MvxViewModel class. Inject the implementation for the IPostService in the constructor method, like this:
Let us focus on the Initialize method in the ViewModel, which is used to do some heavy loading operations, such as loading data from the APIs. It returns a Task, which can be marked as async. Add an override to this method, like this:
publicoverrideasyncTaskInitialize(){ // Async initialization, YEY!awaitbase.Initialize();varresponse=await_postService.GetPostList();if(response.IsSuccess){PostList=newMvxObservableCollection<Post>(response.Result);}else{ // TODO; Show some error messages.}}
That is why I use a ResponseMessage class to encapsulate the result from the APIs. If there are any problems about the HTTP request, this encapsulation is able to make sure the UI layer can deal with the response result correctly because all exceptions and the unexpected values have been handled in the Service layer. If you got a result, which has a False value to the IsSuccess property, show a friendly message to users, rather than throwing an exception.
Then we need to navigate to the PostListViewModel from the FirstViewModel. Update the constructor of the FirstViewModel to inject the IMvxNavigationService, as shown below:
IMvxNavigationService is used to implement the navigation between views. I will describe more about it in the next section. Use the code snippet mvxcmda to create an async command in the FirstViewModel.cs to navigate to the PostListViewModel, like this: