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?
Asked
Active
Viewed 1,992 times
2
-
*"right way to initialize the viewmodel asynchronously"* What do you mean? Perhaps show a snippet of code, with a comment where you would add the "asynchronous" construction. – ToolmakerSteve Jul 22 '22 at 22:49
2 Answers
0
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

Alexandar May - MSFT
- 6,536
- 1
- 8
- 15
-
Thank you for your answer. But I need to call several async methods, so it would be good if I could call them from an async method. But constructor cannot be asynchronous. – David Shochet Jul 25 '22 at 10:12
-
I've updated my answer. You can add an `async` method `Initialize();` in VM and then perform the `await` action. – Alexandar May - MSFT Aug 01 '22 at 03:00
-
But as Initialize() is called synchronously, does it matter that it is async? – David Shochet Aug 01 '22 at 13:21
-
-
0
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.

Tobias Reißmann
- 16
- 1