Store as Observable
Learn about Observable and how the store works with it.
Observable allows libraries like subscribe()
method of the store: when subscribing to the store as an Observable
, the latest state is passed without the need to call store.getState()
.
Redux uses the
symbol-observable
to support older browsers when polyfill It is used to implement features on browsers that do not have support for that feature Symbol.observable
is not natively supported.
Here’s how we can integrate with RxJS:
import store from "store";
import { Observable } from "rxjs";
const store$ = Observable.from(store);
store$.forEach((state) => console.log(state))
This basic API is interoperable with the most common Reactive libraries. Any library that exports the next()
method can subscribe and receive updates.
If you don’t use Reactive libraries, you can still subscribe to the store by accessing the Symbol.observable
property:
const observable = store[Symbol.observable]();
Subscribing with a generic observer will cause the observer’s next()
method to be called on every state change and passed the current store state:
const observer = {
next(state) {
console.log("State change", state);
}
};
const observable = store.$$observable();
const unsubscribe = observable.subscribe(observer);
To unsubscribe, we simply call the function returned from the call to subscribe()
:
const observable = store[Symbol.observable]();
const unsubscribe = observable.subscribe(observer);
unsubscribe();
Get hands-on with 1300+ tech skills courses.