Store as Observable

Learn about Observable and how the store works with it.

Observable allows libraries like RxJSlibrary for composing asynchronous and event-based programs by using observable sequences to subscribe to the store’s state changes. This subscription method is different from the regular 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 polyfillIt is used to implement features on browsers that do not have support for that feature to support older browsers when 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 1200+ tech skills courses.