|
| 1 | +import { Observable, BehaviorSubject, Subject } from 'rxjs' |
| 2 | +import { useState, useEffect, useMemo } from 'react' |
| 3 | + |
| 4 | +const PREFIX = '__SUBJECT__' |
| 5 | + |
| 6 | +const propsSubjects: { |
| 7 | + [index: string]: Subject<any> |
| 8 | +} = {} |
| 9 | + |
| 10 | +let subjectId = 0 |
| 11 | + |
| 12 | +const concatSubjectKey = (id: number) => `${PREFIX}${id}` |
| 13 | + |
| 14 | +export type InputFactory<T, U = undefined> = U extends undefined |
| 15 | + ? () => Observable<T> |
| 16 | + : (props$: Observable<U>) => Observable<T> |
| 17 | + |
| 18 | +export function useObservable<T, U = undefined>(inputFactory: InputFactory<T, U>): T | null |
| 19 | +export function useObservable<T, U = undefined>(inputFactory: InputFactory<T, U>, initialState: T): T |
| 20 | +export function useObservable<T, U extends ReadonlyArray<any>>( |
| 21 | + inputFactory: InputFactory<T, U>, |
| 22 | + initialState: T, |
| 23 | + inputs: U, |
| 24 | +): T |
| 25 | + |
| 26 | +export function useObservable<T, U extends ReadonlyArray<any> | undefined>( |
| 27 | + inputFactory: InputFactory<T, U>, |
| 28 | + initialState?: T, |
| 29 | + inputs?: U, |
| 30 | +): T | null { |
| 31 | + const [state, setState] = useState<[T | null, number]>([initialState || null, 0]) |
| 32 | + if (inputs) { |
| 33 | + useMemo( |
| 34 | + () => { |
| 35 | + const props$ = propsSubjects[concatSubjectKey(state[1])] |
| 36 | + if (props$) { |
| 37 | + props$.next(inputs) |
| 38 | + } |
| 39 | + }, |
| 40 | + inputs as ReadonlyArray<any>, |
| 41 | + ) |
| 42 | + } |
| 43 | + useEffect( |
| 44 | + () => { |
| 45 | + const props$ = new BehaviorSubject<U>(inputs as U) |
| 46 | + const input$ = (inputFactory as (...args: any[]) => Observable<T>)( |
| 47 | + typeof inputs !== 'undefined' ? props$ : void 0, |
| 48 | + ) |
| 49 | + subjectId++ |
| 50 | + const subscription = input$.subscribe((value) => { |
| 51 | + setState([value, subjectId]) |
| 52 | + }) |
| 53 | + propsSubjects[concatSubjectKey(subjectId)] = props$ |
| 54 | + return () => { |
| 55 | + subscription.unsubscribe() |
| 56 | + } |
| 57 | + }, |
| 58 | + [0], // immutable forever |
| 59 | + ) |
| 60 | + return state[0] |
| 61 | +} |
0 commit comments