I use the Async local-storage with angular to store data in the indexedDB.
The library has a method to listen to / watch for changes.
This method returns an Observable with the complete object.
What I want is to slice the changed property value, object, or the array of the object and subscribe to it.
My example object would be:
{
fetched: boolean,
loaded: boolean,
item: null, // object
list: [], // object arry
}
Now I need to watch for the changes in each property as an Observable.
fetched$.subscribe((fetched: boolean)) => {}
loaded$.subscribe((loaded: boolean)) => {}
item$.subscribe((item: any)) => {}
list$.subscribe((list: any[])) => {}
Here is the code I used to slice the changed value so far.
// slice an individual value
function sliceValue<T, U>(
repo: BaseRepository<T, U>,
key: string
): Observable<any> {
if (!repo.key || !repo.store.has(repo.key)) {
return of (null);
}
return repo.store.watch(repo.key).pipe(
distinctUntilChanged((prev, curr) => {
if (!prev || !curr) return false;
return prev[KEY.D][key] === curr[KEY.D][key];
}),
switchMap((ctx: any) => repo.store.get(repo.key)),
map((ctx: any) => ctx[KEY.D][key]));
}
// State class
export class TestState extends BaseRepository<TestModel> {
public fetched$: Observable<boolean> = sliceValue(this, 'fetched');
public loaded$: Observable<boolean> = sliceValue(this, 'loaded');
public item$: Observable<boolean> = sliceObject(this, 'item');
public list$: Observable<string> = sliceList(this, 'list');
constructor(
public readonly store: StorageMap,
) {
super(store);
}
}
But I do not know the efficient way to do it.
If there is any other best way to do it, I would like to know and try it out.
Thank you very much.