mauifreshmvvmmaui-community-toolkitcommunity-toolkit-mvvm

How to initialize ViewModel with CommunityToolkit.Mvvm


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?


Solution

  • 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.