-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathSingletonModelStore.ts
More file actions
80 lines (68 loc) · 2.39 KB
/
SingletonModelStore.ts
File metadata and controls
80 lines (68 loc) · 2.39 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { ModelStore } from 'src/core/modelRepo/ModelStore';
import { Model, type ModelChangedArgs } from 'src/core/models/Model';
import {
type IModelStoreChangeHandler,
type ISingletonModelStore,
type ISingletonModelStoreChangeHandler,
type ModelChangeTagValue,
} from 'src/core/types/models';
import { EventProducer } from '../../shared/helpers/EventProducer';
// Implements logic similar to Android SDK's SingletonModelStore
// Reference: https://github.com/OneSignal/OneSignal-Android-SDK/blob/5.1.31/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/common/modeling/SingletonModelStore.kt
export class SingletonModelStore<TModel extends Model>
implements ISingletonModelStore<TModel>, IModelStoreChangeHandler<TModel>
{
private readonly store: ModelStore<TModel>;
private readonly changeSubscription = new EventProducer<
ISingletonModelStoreChangeHandler<TModel>
>();
constructor(store: ModelStore<TModel>) {
this.store = store;
store._subscribe(this);
}
get model(): TModel {
const model = this.store.list()[0];
if (model) return model;
const createdModel = this.store._create();
if (!createdModel)
throw new Error(`Unable to initialize model from store ${this.store}`);
this.store.add(createdModel);
return createdModel;
}
replace(model: TModel, tag?: ModelChangeTagValue): void {
const existingModel = this.model;
existingModel._initializeFromModel(existingModel._modelId, model);
this.store._persist();
this.changeSubscription._fire((handler) =>
handler._onModelReplaced(existingModel, tag),
);
}
_subscribe(handler: ISingletonModelStoreChangeHandler<TModel>): void {
this.changeSubscription._subscribe(handler);
}
_unsubscribe(handler: ISingletonModelStoreChangeHandler<TModel>): void {
this.changeSubscription._unsubscribe(handler);
}
get _hasSubscribers(): boolean {
return this.changeSubscription._hasSubscribers;
}
/**
* @param {TModel} model
* @param {ModelChangeTagValue)} tag
*/
_onModelAdded(): void {
// No-op: singleton is transparently added
}
_onModelUpdated(args: ModelChangedArgs, tag: ModelChangeTagValue): void {
this.changeSubscription._fire((handler) =>
handler._onModelUpdated(args, tag),
);
}
/**
* @param {TModel} model
* @param {ModelChangeTagValue} tag
*/
_onModelRemoved(): void {
// No-op: singleton is never removed
}
}