Skip to content

Commit 8df1f28

Browse files
committed
Clairify async/syncState
1 parent 673ea88 commit 8df1f28

File tree

1 file changed

+22
-17
lines changed

1 file changed

+22
-17
lines changed

src/index.tsx

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -374,23 +374,6 @@ export function useObservedProp<A>(a: A): Observable<A> {
374374
return useMemo(() => subject.asObservable(), [subject]);
375375
}
376376

377-
export function createSharedState<T>(initialValue: T) {
378-
const subject = new BehaviorSubject(initialValue);
379-
const setState = (value: T | ((prev: T) => T)) => {
380-
if (value instanceof Function) {
381-
subject.next(value(subject.value));
382-
} else {
383-
subject.next(value);
384-
}
385-
};
386-
return Object.assign(subject.asObservable(), {
387-
useState() {
388-
return [useSubscribe(subject, subject.value), setState];
389-
},
390-
setState,
391-
});
392-
}
393-
394377
export function createSharedFetch<T, INPUT extends unknown[], ERR = unknown>(
395378
init$: Observable<RequestInit>,
396379
request: (...input: INPUT) => string,
@@ -418,6 +401,28 @@ export function createSharedFetch<T, INPUT extends unknown[], ERR = unknown>(
418401
};
419402
}
420403

404+
export type SyncState<T> = Observable<T> & {
405+
dispatch: (action: (v: T) => T | T) => T;
406+
unsubscribe: () => void;
407+
};
408+
409+
export function syncState<T>(initialValue: T): SyncState<T> {
410+
const state$ = new BehaviorSubject(initialValue);
411+
const dispatch = (value: T | ((prev: T) => T)) => {
412+
const nextValue = value instanceof Function ? value(state$.value) : value;
413+
if (nextValue !== state$.value) {
414+
state$.next(nextValue);
415+
}
416+
return state$.value;
417+
};
418+
return Object.assign(state$.asObservable(), {
419+
dispatch,
420+
unsubscribe() {
421+
state$.complete();
422+
},
423+
});
424+
}
425+
421426
function isPromise<T>(obj: any): obj is Promise<T> {
422427
return obj && typeof obj.then === 'function';
423428
}

0 commit comments

Comments
 (0)