From 056d22c87e74054f7fb3266dccbd2df866588526 Mon Sep 17 00:00:00 2001 From: Yuriy Durov Date: Fri, 10 May 2024 18:22:22 +0400 Subject: [PATCH] Changes to stateful ViewModel lifecycle --- .../Interfaces/IStatefulViewModel.cs | 5 +++++ src/BitzArt.Blazor.MVVM/Models/PageBase.cs | 4 ++++ src/BitzArt.Blazor.MVVM/Models/ViewModel.cs | 18 ++++++++++++------ 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/BitzArt.Blazor.MVVM/Interfaces/IStatefulViewModel.cs b/src/BitzArt.Blazor.MVVM/Interfaces/IStatefulViewModel.cs index 3e88574..f53179e 100644 --- a/src/BitzArt.Blazor.MVVM/Interfaces/IStatefulViewModel.cs +++ b/src/BitzArt.Blazor.MVVM/Interfaces/IStatefulViewModel.cs @@ -7,5 +7,10 @@ internal interface IStatefulViewModel public void InitializeState(); public Task InitializeStateAsync(); + public void OnStateRestored(); + public Task OnStateRestoredAsync(); + + public void OnStateChanged(); + public Task OnStateChangedAsync(); } diff --git a/src/BitzArt.Blazor.MVVM/Models/PageBase.cs b/src/BitzArt.Blazor.MVVM/Models/PageBase.cs index 33c6c86..859070b 100644 --- a/src/BitzArt.Blazor.MVVM/Models/PageBase.cs +++ b/src/BitzArt.Blazor.MVVM/Models/PageBase.cs @@ -39,6 +39,7 @@ private static async Task RestoreComponentStateAsync(ViewModel viewModel, string var buffer = Convert.FromBase64String(state); var json = Encoding.UTF8.GetString(buffer); statefulViewModel.State = JsonSerializer.Deserialize(json, statefulViewModel.StateType, StateJsonOptionsProvider.Options)!; + await statefulViewModel.OnStateRestoredAsync(); statefulViewModel.OnStateRestored(); } else @@ -48,6 +49,9 @@ private static async Task RestoreComponentStateAsync(ViewModel viewModel, string statefulViewModel.InitializeState(); await statefulViewModel.InitializeStateAsync(); } + + statefulViewModel.OnStateChanged(); + await statefulViewModel.OnStateChangedAsync(); } /// diff --git a/src/BitzArt.Blazor.MVVM/Models/ViewModel.cs b/src/BitzArt.Blazor.MVVM/Models/ViewModel.cs index b785329..2c2702c 100644 --- a/src/BitzArt.Blazor.MVVM/Models/ViewModel.cs +++ b/src/BitzArt.Blazor.MVVM/Models/ViewModel.cs @@ -33,11 +33,7 @@ public abstract class ViewModel : ViewModel, IStatefulViewModel public TState State { get => _state; - set - { - _state = value; - OnStateChanged(State); - } + set => _state = value; } object IStatefulViewModel.State @@ -69,8 +65,18 @@ public virtual Task InitializeStateAsync() /// public virtual void OnStateRestored() { } + public virtual Task OnStateRestoredAsync() + { + return Task.CompletedTask; + } + /// /// Called when the state has changed. /// - public virtual void OnStateChanged(TState state) { } + public virtual void OnStateChanged() { } + + public virtual Task OnStateChangedAsync() + { + return Task.CompletedTask; + } }