Search code examples
c#avaloniaui

Avalonia 11 RxApp.SuspensionHost.GetAppState<AppState>() returns null, while v 0.10 does not


The code that works in Avalonia 0.10 does not behave the same way in 11. It used to return an object but now returns null.
How is it supposed to be solved?

var state = RxApp.SuspensionHost.GetAppState<AppState>();

The code is like the official documentation.

App.axaml.cs:

OnFrameworkInitializationCompleted(){
   ...
   var suspension = new AutoSuspendHelper(ApplicationLifetime);
   RxApp.SuspensionHost.CreateNewAppState = () => new AppState();
   RxApp.SuspensionHost.SetupDefaultSuspendResume(new NewtonsoftJsonSuspensionDriver(appStatePath));
   suspension.OnFrameworkInitializationCompleted();
   var state = RxApp.SuspensionHost.GetAppState<AppState>();
   ...
}

When I have no instantiated AppState I cannot save the application's state like the documentation says, as the call to NewtonsoftJsonSuspensionDriver.SaveState(object state) receives state==null.

I tried the trick to create an AppState on the fly like so:

var state = RxApp.SuspensionHost.GetAppState<AppState>() ?? new AppState();

but NewtonsoftJsonSuspensionDriver.SaveState(object state) receives state==null.

I see nothing about the changed behaviour in the official update document.
For the very curious the update is a commit in Github.


Solution

  • I guess it is expected behaviour. When the file (appStatePath) exists the call returns null.
    When the file exists an object is returned.


    Above is the answer.
    Below comes the situation which fooled me.

    See Question in Avolonia site.
    (Avalonia knowledge requried).

    I had overloaded a method in MainWindow.xaml.cs

     public override async void Show()
    

    that ended up in making the call

    (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)
        .Windows[0];
    

    and as Windows is null the "application state manager" decided that there is no state and removed the file where the state should be stored.

    Now note that this is in the designer inside my IDE (Rider @ macm2). I don't have any visual designer open, just the text files. But code was run and I was fooled.

    The remedy is to wrap the culprit call in a if (Avalonia.Controls.Design.IsDesignMode == false)

    The culprit has nothing to do with the behaviour of RxApp.SuspensionHost.GetAppState() and nothing to do with any update of Avalonia to 11.