-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathComponentStatePersister.cs
39 lines (31 loc) · 1.19 KB
/
ComponentStatePersister.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Components;
namespace BlazorWasmApp1;
public class ComponentStatePersister : IComponentStatePersister
{
private readonly PersistentComponentState _persistentState;
private readonly PersistingComponentStateSubscription _subscription;
private readonly ConcurrentDictionary<string, IPersistableState> _stateItems = new();
public ComponentStatePersister(PersistentComponentState persistentState)
{
this._persistentState = persistentState;
this._subscription = this._persistentState.RegisterOnPersisting(this.OnPersisting);
}
public async ValueTask<T?> GetAsync<T>(string key, Func<ValueTask<T?>> getAsync)
{
var stateItem = this._stateItems.GetOrAdd(key, _ => new ComponentStateItem<T>(key, getAsync)) as ComponentStateItem<T>;
return await stateItem!.GetAsync(this._persistentState);
}
private Task OnPersisting()
{
foreach (var stateItem in this._stateItems.Values)
{
stateItem.PersistAsJson(this._persistentState);
}
return Task.CompletedTask;
}
public void Dispose()
{
this._subscription.Dispose();
}
}