Skip to content

Commit

Permalink
add possibility to reset and feed store, reset clears hydration so th…
Browse files Browse the repository at this point in the history
…e store can be rehydrated if needed while feed is just replacing the state without other flags being updated apart from the property listeners (#13)
  • Loading branch information
JuliusKoronciCH authored Apr 18, 2024
1 parent f3a8629 commit 5233bf9
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
58 changes: 57 additions & 1 deletion lib/event-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,23 @@ export function createEventStore<T extends object>(
);
};

const getResetObservable$ = (): Observable<T> => {
return globalEventStore$.pipe(
filter((event) => event.type === '@@RESET'),
map((event) => event.payload as T),
scan((__, curr) => curr),
distinctUntilChanged(),
);
};
const getFeedObservable$ = (): Observable<T> => {
return globalEventStore$.pipe(
filter((event) => event.type === '@@FEED'),
map((event) => event.payload as T),
scan((__, curr) => curr),
distinctUntilChanged(),
);
};

const state$ = new BehaviorSubject<T>(initialState);

globalEventStore$
Expand All @@ -80,7 +97,12 @@ export function createEventStore<T extends object>(
}
}),
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;
}

Expand Down Expand Up @@ -134,6 +156,29 @@ export function createEventStore<T extends object>(
};
}, []);

useEffect(() => {
const subscription = getResetObservable$().subscribe({
next: (nextState) => {
setValue(get(type, nextState) as GetValueType<T, K>);
},
});

return () => {
subscription.unsubscribe();
};
}, []);
useEffect(() => {
const subscription = getFeedObservable$().subscribe({
next: (nextState) => {
setValue(get(type, nextState) as GetValueType<T, K>);
},
});

return () => {
subscription.unsubscribe();
};
}, []);

useEffect(() => {
const subscription = getPropertyObservable(
type,
Expand Down Expand Up @@ -169,6 +214,17 @@ export function createEventStore<T extends object>(
subscription.unsubscribe();
};
}, []);
useEffect(() => {
const subscription = getResetObservable$().subscribe({
next: () => {
setIsHydrated(false);
},
});

return () => {
subscription.unsubscribe();
};
}, []);

return useMemo(() => isHydrated, [isHydrated]);
};
Expand Down
4 changes: 3 additions & 1 deletion lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ export interface NestedEvent<T> {
}
export type SystemEvent<T> =
| { type: '@@INIT'; payload: T }
| { type: '@@HYDRATED'; payload: T };
| { type: '@@HYDRATED'; payload: T }
| { type: '@@RESET'; payload: T }
| { type: '@@FEED'; payload: T };

0 comments on commit 5233bf9

Please sign in to comment.