import { Observable } from "rxjs"; import { useState, useEffect, Dispatch, SetStateAction } from "react"; import { noop } from "shared/helpers/function.helpers"; export function useSwitchableObservable(observable?: Observable, clearOnSwitch = true): [T, Dispatch>>, Observable, Dispatch>] { const [currentObs, setCurrentObs] = useState(observable); const [obsValue, setObsValue] = useState(); useEffect(() => { if (!currentObs) { return noop; } if (clearOnSwitch) { setObsValue(() => null); } const sub = currentObs.subscribe(val => setObsValue(() => val)); return () => { sub.unsubscribe(); }; }, [currentObs]); return [obsValue, setCurrentObs, currentObs, setObsValue]; }