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.