Home > Software design >  Getting initial data pattern in Xamarin Forms
Getting initial data pattern in Xamarin Forms

Time:02-26

I'm trying to understand the pattern to use in Xamarin Forms when a page gets its initial data from a web API.

The page is tied to a ViewModel. Let's use this simple example:

public class DataFeedViewModel : BaseViewModel
{
   public DateFeedViewModel()
   {
       Title = "My Feed";
   }

   public List<FeedItem> Feed { get; set; }

}

The DataFeedViewModel is bound to the page:

public MainPage()
{
    InitializeComponent();
    this.BindingContext = new DataFeedViewModel();
}

As I understand it, I use the OnAppearing() method to fetch my initial set of data from the backend API:

protected override async void OnAppearing()
{
    base.OnAppearing();

    var result = await _myApiService.GetFeed();
    // What's next? Do I simply do the following?
    // new DataFeedViewModel
    // {
    //     Feed = result
    // }
}

Also a second but very important question is whether this pattern is the recommended approach.

As I learn about Xamarin and .NET Maui, I understand, the trend is to go from an event driven model to a more MVVM command driven approach.

I'm a bit confused about how to use a ViewModel to tap into these life cycle methods such as OnAppearing().

CodePudding user response:

create an Init method on your VM

public class DataFeedViewModel : BaseViewModel
{
   public DateFeedViewModel()
   {
       Title = "My Feed";
   }

   public List<FeedItem> Feed { get; set; }

   public async void Init()
   {
       Feed = await _myApiService.GetFeed();
   }
}

and then have your page call it

private DataFeedViewModel VM { get; set; }

public MainPage()
{
    InitializeComponent();
    this.BindingContext = VM = new DataFeedViewModel();
}

protected override async void OnAppearing()
{
    base.OnAppearing();

    await VM.Init();
}
  • Related