Created
February 20, 2023 03:28
-
-
Save wangpin34/a7e5d1d1df9892aec9ecbad20434a044 to your computer and use it in GitHub Desktop.
react-rxjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react" | |
import { BehaviorSubject, Observable, filter, shareReplay } from "rxjs" | |
export function createSignal<T>(initialValue?: T) { | |
const v$ = new BehaviorSubject<T | undefined>(initialValue) | |
const setValue = (v: T) => { | |
v$.next(v) | |
} | |
return [v$, setValue] as [BehaviorSubject<T>, (v: T) => void] | |
} | |
function _useValue<T>(shareReplay$: Observable<T>, defaultValue?: T) { | |
const [value, setValue] = useState<T | undefined>(defaultValue) | |
useEffect(() => { | |
const subscriber = shareReplay$.subscribe((v) => { | |
setValue(v) | |
}) | |
return () => { | |
subscriber.unsubscribe() | |
} | |
}, [shareReplay$]) | |
return value | |
} | |
export function bind<T>(observable: BehaviorSubject<T>, defaultValue?: T) { | |
if (typeof defaultValue !== "undefined") { | |
observable.next(defaultValue) | |
} | |
const shareReplay$ = observable.asObservable().pipe( | |
shareReplay(1), | |
filter((v) => typeof v !== "undefined"), | |
) | |
const useValue = () => _useValue(shareReplay$, defaultValue) | |
return [useValue, shareReplay$] as [() => T, Observable<T>] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a replacement if you don't want to install @react-rxjs/core @react-rxjs/utils but want to use the basic tools it provided. it works as expected but react-hooks/rules-of-hooks keeps alerting that is boring and I have no idea how to disable the lint. Tried with inline comment on right above the useXXX but not works.