Skip to content

Commit

Permalink
fix: child property observable (#16)
Browse files Browse the repository at this point in the history
* make sure property observable fires on exact property match

* add obervable for child property changes
  • Loading branch information
JuliusKoronciCH authored Apr 25, 2024
1 parent 2c3a297 commit 6d33779
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lib/event-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ export function createEventStore<T extends object>(
return observable;
};

const getChildPropertyObservable = <K extends PropertyPath<T>>(
eventType: K,
throttle?: number,
) => {
const observable = globalEventStore$.pipe(
filter((event) => event.type.startsWith(`${eventType}.`)),
share({ connector: () => new Subject(), resetOnRefCountZero: true }),
);
if (throttle) {
observable.pipe(auditTime(throttle));
}
return observable;
};

const getHydrationObservable$ = (): Observable<T> => {
return globalEventStore$.pipe(
filter((event) => event.type === '@@HYDRATED'),
Expand Down Expand Up @@ -144,6 +158,11 @@ export function createEventStore<T extends object>(
publish(type, payload);
}, []);

const restoreValueFromState$ = () => {
const stateValue: GetValueType<T, K> = get(type, state$.getValue());
setValue(stateValue);
};

useEffect(() => {
const subscription = getHydrationObservable$().subscribe({
next: (nextState) => {
Expand Down Expand Up @@ -192,6 +211,20 @@ export function createEventStore<T extends object>(
subscription.unsubscribe();
};
}, []);
useEffect(() => {
const subscription = getChildPropertyObservable(
type,
options?.throtle,
).subscribe({
next: (event) => {
if (debug) console.log('CHILD PROPERTY OBSERVABLE', event);
setTimeout(restoreValueFromState$);
},
});
return () => {
subscription.unsubscribe();
};
}, []);

return [value, handleUpdate];
};
Expand Down

0 comments on commit 6d33779

Please sign in to comment.