UNPKG

rxjs-hooks

Version:
36 lines 1.45 kB
import { BehaviorSubject } from 'rxjs'; import { tap } from 'rxjs/operators'; import { useEffect, useMemo } from 'react'; import useConstant from 'use-constant'; import { useSyncExternalStore } from 'use-sync-external-store/shim'; export function useObservable(inputFactory, initialState, inputs) { var state$ = useConstant(function () { return new BehaviorSubject(initialState); }); var inputs$ = useConstant(function () { return new BehaviorSubject(inputs); }); useEffect(function () { return function () { state$.complete(); inputs$.complete(); }; }, []); useEffect(function () { inputs$.next(inputs); }, inputs || []); var subscribe = useMemo(function () { var output$; if (inputs) { output$ = inputFactory(state$, inputs$); } else { output$ = inputFactory(state$); } return function (onStorageChange) { var subscription = output$.pipe(tap(function (s) { return state$.next(s); })).subscribe(onStorageChange); return function () { return subscription.unsubscribe(); }; }; }, []); var getSnapShot = useMemo(function () { return function () { var _a; return (_a = state$.getValue()) !== null && _a !== void 0 ? _a : null; }; }, []); return useSyncExternalStore(subscribe, getSnapShot, getSnapShot); } //# sourceMappingURL=use-observable.js.map