Álvaro García
Álvaro García

Reputation: 19396

In a MAUI application, where is the best way to initialize some data when the application starts?

I have a MAUI application and I would like to initialize some data of the application when the application starts.

In my case, I have a default settings applications that is added as resource when I compile. In the startup, I check if I have any of this settings in Prefereces.Default, that is the storage of the application. If not, I copy the settings from the embedded resource to References.Default.

By the moment I am doing this in the MauiProgram.cs file, but I am not sure if this is the best place to do it.

Perhaps AppShell.xaml.cs is another possible place or perhaps app.xaml.cs.

Where should do this initialization?

where is the use of AppShell, App and MauiProgram?

Thanks.

Upvotes: 7

Views: 3503

Answers (1)

Sir Rufo
Sir Rufo

Reputation: 19106

Declare a page for initialization and use that as the App.MainPage. When the initialization is done change the App.MainPage to an AppShell instance.

public partial class App : Application
{
    public App( InitPage init, AppShell shell )
    {
        InitializeComponent();
        // InitPage notifies on completion, so we change the MainPage to shell
        init.InitCompleted += ( s, e ) => MainPage = shell;
        MainPage = init;
    }
}

InitPage starts the initialization on appearing. The initialization itself is done inside the ViewModel

public partial class InitPage : ContentPage
{
    public InitPage( InitPageViewModel viewModel )
    {
        InitializeComponent();
        BindingContext = viewModel;
        Appearing += async ( s, e ) =>
        {
            await viewModel.InitializeAsync();
            InitCompleted?.Invoke( this, EventArgs.Empty );
        };
    }

    public event EventHandler<EventArgs> InitCompleted;
}

The ViewModel now can initialize any needed services

public class InitPageViewModel : ViewModelBase
{
    [Reactive] public string InitSection { get; private set; }
    protected override async Task OnInitializeAsync( CancellationToken cancellationToken )
    {
        await base.OnInitializeAsync( cancellationToken );
        InitSection = "Warm up DataServices";
        await Task.Delay( 2000 );
        InitSection = "Expand Images";
        await Task.Delay( 4000 );
        InitSection = "Feed the pets";
        await Task.Delay( 3000 );
    }
}

A full sample app is on github

Upvotes: 3

Related Questions