Xamarin & MvvmCross Handbook
  • Introduction
  • Using MvvmCross to create your first Xamarin App
    • Creating the Core project
      • Understanding MVVM
      • Adding a simple Service
      • Adding a ViewModel
      • Adding an App class
    • Creating the Android project
      • Adding an Android Application class
      • Adding the Android Layout View (AXML)
      • Understanding the data-binding syntax
      • Adding the View class
    • Creating the iOS project
      • Updating the AppDelegate class
      • Adding the iOS View for the first ViewModel
      • Understanding the data-binding syntax
    • Creating the UWP project
      • Updating the App.xaml.cs and the App.xaml
      • Adding the UWP View
      • Understanding the data-binding syntax
    • Creating the REST API Service
      • Creating the models
      • Creating the interface and the implementation for the PostService
      • Creating the ViewModel
      • Adding the View for the Android project
      • Adding the View for the iOS project
      • Adding the View for the UWP project
    • Navigation
      • Creating the PostDetail View & ViewModel
      • Command with the parameter
      • Retrieving the param from the previous ViewModel
      • Understanding the IMvxNavigationService
      • Responding the events from different controls in the ListView
      • Retrieving the return result from the previous ViewModel
    • Creating the Xamarin.Forms project
      • Creating the Forms.UI project
      • Adding the App.xaml and the App.xaml.cs
      • Adding the View
      • Creating the Android project
      • Creating the iOS project
      • Creating the UWP project
      • Summary For Forms
    • Summary
  • Implementing MasterDetail layout in Xamarin.Forms by MvvmCross
    • Introduction
    • Creating the project by MvxScaffolding
    • Creating the MasterDetailPage
      • Creating the ViewModel
      • Creating the XAML file
    • Creating the MasterPage
      • Creating the ViewModel
      • Creating the XAML file
    • Creating the DetailPages
      • Creating the ViewModels
      • Creating the XAML files
    • Implementing the Menu functionalities
      • Displaying the MasterPage and the DetailPage
      • Setting the menu navigation
      • The other approaches to set the data-binding
    • Fine-tuning the UI
      • Adding the hamburger icon for iOS
      • Adding the header bar for Android and iOS
      • Adjust the height of the item for UWP
    • Summary
Powered by GitBook
On this page

Was this helpful?

  1. Using MvvmCross to create your first Xamarin App
  2. Creating the REST API Service

Creating the interface and the implementation for the PostService

Create a new interface called IPostService.cs into the Services folder in the MvvmCrossDemo.Core project. Add two methods to it, as shown below:

namespace MvvmCrossDemo.Core.Services
{
    public interface IPostService
    {
        Task<ResponseMessage<List<Post>>> GetPostList();
        Task<ResponseMessage<Post>> GetPost(int id);
    }
}

Create a new implementation class called PostService.cs in the same folder like this:

using System;
using MvvmCrossDemo.Core.Infrastructure.Extensions;
using MvvmCrossDemo.Core.Models;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace MvvmCrossDemo.Core.Services
{
    public class PostService : IPostService
    {
        private readonly HttpClient _httpClient;
        private string apiUrl = "https://jsonplaceholder.typicode.com/";

        public PostService()
        {
            _httpClient = new HttpClient();
        }

        public async Task<ResponseMessage<List<Post>>> GetPostList()
        {
            try
            {
                var response = await _httpClient.GetAsync($"{apiUrl}posts");
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var result = await response.ReadAsJsonAsync<List<Post>>();
                    return new ResponseMessage<List<Post>>
                    {
                        IsSuccess = true,
                        Result = result
                    };
                }
                else
                {
                    return new ResponseMessage<List<Post>>
                    {
                        IsSuccess = false,
                        // Show the detailed error message here according to the response.
                        Message = "Errors"
                    };
                }
            }
            catch (Exception e)
            {
                // TODO: Log the exception here.
                return new ResponseMessage<List<Post>>
                {
                    IsSuccess = false,
                    // Show the detailed error message here.
                    Message = "Errors"
                };
            }
            
        }
        public async Task<ResponseMessage<Post>> GetPost(int id)
        {
            try
            {
                var response = await _httpClient.GetAsync($"{apiUrl}posts/{id}");
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var result = await response.ReadAsJsonAsync<Post>();
                    return new ResponseMessage<Post>
                    {
                        IsSuccess = true,
                        Result = result
                    };
                }
                else
                {
                    return new ResponseMessage<Post>
                    {
                        IsSuccess = false,
                        // Show the detailed error message here according to the response.
                        Message = "Errors"
                    };
                }
            }
            catch (Exception e)
            {
                // TODO: Log the exception here.
                return new ResponseMessage<Post>
                {
                    IsSuccess = false,
                    // Show the detailed error message here.
                    Message = "Errors"
                };
            }
        }
    }
}

In the PostService class, I tried to handle all exceptions of the HTTP requests to avoid passing any unexpected result to the caller method. It is helpful to improve the stability of the App. We also need to use a logger to record the error message if you are developing a real App.

We do not need to worry about how to register the implement instance because MvvmCross will do everything by the code we mentioned before in the App.cs, as long as we follow the name convention of the services:

CreatableTypes().EndingWith("Service").AsInterfaces().RegisterAsLazySingleton();
PreviousCreating the modelsNextCreating the ViewModel

Last updated 6 years ago

Was this helpful?