Skip to content

Instantly share code, notes, and snippets.

@wangpin34
Created February 20, 2023 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wangpin34/a7e5d1d1df9892aec9ecbad20434a044 to your computer and use it in GitHub Desktop.
Save wangpin34/a7e5d1d1df9892aec9ecbad20434a044 to your computer and use it in GitHub Desktop.
react-rxjs
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>]
}
@wangpin34
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment