Skip to content
This repository has been archived by the owner on Nov 1, 2024. It is now read-only.

Commit

Permalink
Changes to stateful ViewModel lifecycle
Browse files Browse the repository at this point in the history
  • Loading branch information
YuriyDurov committed May 10, 2024
1 parent 0f8633b commit 056d22c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
5 changes: 5 additions & 0 deletions src/BitzArt.Blazor.MVVM/Interfaces/IStatefulViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
4 changes: 4 additions & 0 deletions src/BitzArt.Blazor.MVVM/Models/PageBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -48,6 +49,9 @@ private static async Task RestoreComponentStateAsync(ViewModel viewModel, string
statefulViewModel.InitializeState();
await statefulViewModel.InitializeStateAsync();
}

statefulViewModel.OnStateChanged();
await statefulViewModel.OnStateChangedAsync();
}

/// <summary>
Expand Down
18 changes: 12 additions & 6 deletions src/BitzArt.Blazor.MVVM/Models/ViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,7 @@ public abstract class ViewModel<TState> : ViewModel, IStatefulViewModel
public TState State
{
get => _state;
set
{
_state = value;
OnStateChanged(State);
}
set => _state = value;
}

object IStatefulViewModel.State
Expand Down Expand Up @@ -69,8 +65,18 @@ public virtual Task InitializeStateAsync()
/// </summary>
public virtual void OnStateRestored() { }

public virtual Task OnStateRestoredAsync()
{
return Task.CompletedTask;
}

/// <summary>
/// Called when the state has changed.
/// </summary>
public virtual void OnStateChanged(TState state) { }
public virtual void OnStateChanged() { }

public virtual Task OnStateChangedAsync()
{
return Task.CompletedTask;
}
}

0 comments on commit 056d22c

Please sign in to comment.