How to initialize ViewModel with CommunityToolkit.Mvvm

2.9k Views Asked by At

We have a Xamarin.Forms app with FreshMvvm. Now, as Xamarin.Forms will not get support beginning next year, I am re-writing the app with .Net Maui. For MVVM pattern, I am trying to use CommunityToolkit.Mvvm. But I wonder how I can initialize the viewmodel now. With FreshMvvm I could override Init(), but CommunityToolkit.Mvvm does not seem to have anything like this. What is the right way to initialize the viewmodel asynchronously, as there is no async constructor?

2

There are 2 best solutions below

0
Tobias Reißmann On BEST ANSWER

I started with .net Maui a weeks ago and also needed the possibility to run async code in the constructor of the view model. I found the method SafeFireAndForget from AsyncAwaitBestPractices (nuget package). The async code will run in a different thread and the constructor may will complete before the async method.

5
Alexandar May - MSFT On

In FreshMVVM, since the model has impelmented the FreshBasePageModel, you can override the Init() method and initialize data like the pseudo code below:

   public override void Init (object initData)
    {           
      //initialize data
    }

However, in CommunityToolkit.Mvvm, you can set the data whatever you want in the default constructor like below:

public partial class MainPage : ContentPage
{
    public MainPage(MainPageViewModel vm)
    {
        InitializeComponent();

        BindingContext = vm;

        Initialize();
    }
    public async void Initialize()
    {
        //await operation
    }

}

Official reference link:https://learn.microsoft.com/en-us/windows/communitytoolkit/mvvm/introduction