Calling Asynchronous method from ViewModel Constructor Xamarin.Forms

Viewed 9051

I can't find a straight example from a-z on how to implement calling an async method from a constructor in a safe way. Following is what I've come up with but I don't understand the concepts that well so I have no idea if it's really correct or not. Can someone bless this format?

Create IAsyncInitialization interface:

/// <summary>
/// The result of the asynchronous initialization of this instance.
/// see http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html
/// </summary>
Task Initialization { get; }

Slap the interface on this ViewModel then...:

public GotoViewModel() // constructor
{
    Initialization = InitializeAsync();
}

public Task Initialization { get; private set; }
private async Task InitializeAsync()
{
    //call some async service and get data
}

From the code-behind xaml.cs that uses this ViewModel:

public partial class GotoPage : ContentPage, IAsyncInitialization
{
    IGotoViewModel VM;
    public GotoPage()
    {
         InitializeComponent();
         VM = App.Container.Resolve<IGotoViewModel>();
         Initialization = InitializeAsync();
     }

     public Task Initialization { get; private set; }

     private async Task InitializeAsync()
     {
          await VM.Initialization;
          this.BindingContext = VM;
     }
}

This code works great but I know that doesn't mean much.

3 Answers

Since I posted this question and for over a year now in my projects I've been going without any MVVM framework because I can't stand being tied to a framework that may break with the latest Xamarin.Forms. I ended up calling my async init method in my viewmodel from the xaml's appearing event tied to a behavior.

Related