From 5233bf90f20ea641d2bd79f21d11907e27799720 Mon Sep 17 00:00:00 2001 From: JuliusKoronciCH <165957874+JuliusKoronciCH@users.noreply.github.com> Date: Thu, 18 Apr 2024 10:41:41 +0200 Subject: [PATCH] add possibility to reset and feed store, reset clears hydration so the store can be rehydrated if needed while feed is just replacing the state without other flags being updated apart from the property listeners (#13) --- lib/event-store.ts | 58 +++++++++++++++++++++++++++++++++++++++++++++- lib/types.ts | 4 +++- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/lib/event-store.ts b/lib/event-store.ts index 19315c2..fad53fe 100644 --- a/lib/event-store.ts +++ b/lib/event-store.ts @@ -70,6 +70,23 @@ export function createEventStore( ); }; + const getResetObservable$ = (): Observable => { + return globalEventStore$.pipe( + filter((event) => event.type === '@@RESET'), + map((event) => event.payload as T), + scan((__, curr) => curr), + distinctUntilChanged(), + ); + }; + const getFeedObservable$ = (): Observable => { + return globalEventStore$.pipe( + filter((event) => event.type === '@@FEED'), + map((event) => event.payload as T), + scan((__, curr) => curr), + distinctUntilChanged(), + ); + }; + const state$ = new BehaviorSubject(initialState); globalEventStore$ @@ -80,7 +97,12 @@ export function createEventStore( } }), scan((state, event) => { - if (event.type === '@@INIT' || event.type === '@@HYDRATED') { + if ( + event.type === '@@INIT' || + event.type === '@@HYDRATED' || + event.type === '@@RESET' || + event.type === '@@FEED' + ) { return event.payload as T; } @@ -134,6 +156,29 @@ export function createEventStore( }; }, []); + useEffect(() => { + const subscription = getResetObservable$().subscribe({ + next: (nextState) => { + setValue(get(type, nextState) as GetValueType); + }, + }); + + return () => { + subscription.unsubscribe(); + }; + }, []); + useEffect(() => { + const subscription = getFeedObservable$().subscribe({ + next: (nextState) => { + setValue(get(type, nextState) as GetValueType); + }, + }); + + return () => { + subscription.unsubscribe(); + }; + }, []); + useEffect(() => { const subscription = getPropertyObservable( type, @@ -169,6 +214,17 @@ export function createEventStore( subscription.unsubscribe(); }; }, []); + useEffect(() => { + const subscription = getResetObservable$().subscribe({ + next: () => { + setIsHydrated(false); + }, + }); + + return () => { + subscription.unsubscribe(); + }; + }, []); return useMemo(() => isHydrated, [isHydrated]); }; diff --git a/lib/types.ts b/lib/types.ts index 7636ef6..26f7963 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -27,4 +27,6 @@ export interface NestedEvent { } export type SystemEvent = | { type: '@@INIT'; payload: T } - | { type: '@@HYDRATED'; payload: T }; + | { type: '@@HYDRATED'; payload: T } + | { type: '@@RESET'; payload: T } + | { type: '@@FEED'; payload: T };