atomWithObservable
Ref: https://github.com/pmndrs/jotai/pull/341
Usage
import { useAtom } from 'jotai'import { atomWithObservable } from 'jotai/utils'import { interval } from 'rxjs'import { map } from "rxjs/operators"const counterSubject = interval(1000).pipe(map((i) => `#${i}`));const counterAtom = atomWithObservable(() => counterSubject);const Counter = () => {const [counter] = useAtom(counterAtom)return <div>count: {counter}</div>;}
The atomWithObservable
function creates an atom from a rxjs (or similar) subject
or observable
.
Its value will be last value emitted from the stream.
To use this atom, you need to wrap your component with <Suspense>
. Check out basics/async.
Initial value
atomWithObservable
takes second optional parameter { initialValue }
that allows to specify initial value for the atom. If initialValue
is provided then atomWithObservable
will not suspend and will show initial value before receiving first value from observable. initialValue
can be either a value or a function that returns a value
const counterAtom = atomWithObservable(() => counterSubject, {initialValue: 10});const counterAtom2 = atomWithObservable(() => counterSubject, {initialValue: () => Math.random()});
Timeout
To prevent memory leaks, the subscription to the observable is cancelled if no initial value was omitted after ten seconds.
You can change this value via the timeout
option.
You can disable the timeout
by setting the value to false
.
const counterAtomWithOneSecondTimeout = atomWithObservable(() => counterSubject, {timeout: 1000});const counterAtomWithoutTimeout = atomWithObservable(() => counterSubject, {timeout: false});