@@ -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-
394377export 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+
421426function isPromise < T > ( obj : any ) : obj is Promise < T > {
422427 return obj && typeof obj . then === 'function' ;
423428}
0 commit comments