zustand-rx
v2.1.0
Published
This is a tool to subscribe to a Zustand store as an RxJS observable.
Downloads
8,121
Readme
zustand-rx
This is a tool to subscribe to a Zustand store as an RxJS observable.
Compatible versions
It has been tested with RxJS v7.x and Zustand v3.x/v4.x, though other versions may work too.
Install
npm install zustand-rx zustand rxjs
yarn add zustand-rx zustand rxjs
pnpm add zustand-rx zustand rxjs
Usage
import { toStream } from 'zustand-rx';
import { combine } from 'zustand/middleware';
import create from 'zustand/vanilla';
// NOTE: alternatively, the React version also seems to work:
// import create from 'zustand';
const store = create(
combine({ bears: 0 }, (set) => ({
increase: (by: number) => set((state) => ({ bears: state.bears + by })),
})),
);
// type is Observable<number>
const bears$ = toStream(store, (state) => state.bears, {
fireImmediately: true,
});
Using fireImmediately
is similar to a BehaviorSubject
.
For UI integrations, for example, using Angular with AsyncPipe, you probably want to set fireImmediately
to true.
You can also provide an equalityFn
. This works the same as Zustand's equality function.