adospace / reactorui-maui

MauiReactor is a MVU UI framework built on top of .NET MAUI
MIT License
586 stars 49 forks source link

Application lifecycle events #49

Closed NickDarvey closed 1 year ago

NickDarvey commented 1 year ago

Is there a recommended way to hook into application lifecycle events?

It looks like they're available on ReactorApplication<> if I derive my own application class

https://github.com/adospace/reactorui-maui/blob/7de43399d1a2c891910c9db501d2b173f7614d7d/src/MauiReactor/ReactorApplication.cs#L296-L315

and instantiate it myself.

https://github.com/adospace/reactorui-maui/blob/7de43399d1a2c891910c9db501d2b173f7614d7d/src/MauiReactor/ReactorApplication.cs#L327-L334

NickDarvey commented 1 year ago

Ah, except ServiceCollectionProvider.ServiceProvider is internal.

https://github.com/adospace/reactorui-maui/blob/7de43399d1a2c891910c9db501d2b173f7614d7d/src/MauiReactor/ReactorApplication.cs#L330

It's a static global thing, so it's probably good that it's internal.

Perhaps there could be a builder extension that allows you to use your own app type?

 public static MauiAppBuilder UseMauiReactorAppWith<TComponent, TApp>(this MauiAppBuilder appBuilder, Fun<IServiceProvider, TApp> createApplication, Action<Application>? configureApplication = null)
  where TComponent : Component, new()
  where TApp : ReactorApp<TComponent>
     => appBuilder.UseMauiApp(sp =>  
     { 
         ServiceCollectionProvider.ServiceProvider = sp; 
         var app = createApplication(sp); 
         configureApplication?.Invoke(app); 
         return app; 
     }); 
adospace commented 1 year ago

Hi, I don't think you need to override the Application type (even if I could allow it in the future).

You could just provide your Window and attach the events you need:

class MainPage : Component
{
    public override VisualNode Render()
    {
        return new Window
        {
            new ContentPage
            {
            }
        }
        .OnCreated(OnMainWindowCreated)
        .OnStopped(OnMainWindowStopped)
        ;
    }

    private void OnMainWindowCreated()
    {
        System.Diagnostics.Debug.WriteLine("Window created");
    }

    private void OnMainWindowStopped()
    {
        System.Diagnostics.Debug.WriteLine("Window stopped");
    }
}

For others looking at this thread this is the list of callbacks provided by the Application type: https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/app-lifecycle?view=net-maui-7.0