flippant remarks about BehaviorSubject
It feels like BehaviorSubject
was built to make observable store services possible. BehaviorSubject
is at the heart of the possibility of never needing a large/complex package like Redux—ever. In “State management in Angular with observable store services,” Jure Bajt writes:
…we used the ideas from Redux to create a state management solution that leverages Angular’s (and RxJS’s) features to do its job…
Jure Bajt developed rxjs-observable-store
[GitHub] to avoid “pitfall # 1” in “How to build Angular apps using Observable Data Services - Pitfalls to avoid”:
…we don’t expose the subject directly to store clients, instead, we expose an observable… Exposing the subject directly could lead to event soup applications, where events get chained together in a hard to reason way.
To avoid the overhead of managing Bajt’s offering as a package, this is the essential:
import {Observable, BehaviorSubject} from 'rxjs';
export class Store<T> {
state$: Observable<T>;
private _state$: BehaviorSubject<T>;
protected constructor (initialState: T) {
this._state$ = new BehaviorSubject(initialState);
this.state$ = this._state$.asObservable();
}
get state (): T {
return this._state$.getValue();
}
setState (nextState: T): void {
this._state$.next(nextState);
}
}
no, really: what about Redux and ngrx?
Jure Bajt addresses those that recommend Redux:
The solution we developed is a really stripped down version of Redux. It does not “prescribe” how to handle async actions, how to combine reducers, how to implement middleware etc. Its only role is to provide a simple API to update state object and to subscribe to its updates. Stores are otherwise just good ol’ Angular service classes.
Basjt addresses users of ngrx
[home]:
I used ngrx in the past and I think it is a really good library for state management. But it also takes longer to learn it, because of all the features it supports. …one may not need a full blown state management library to manage state even in larger applications… I believe less complexity comes from the fact that observable store services heavily depend on Angular features (dependency injection, async pipes etc.) to do a lot of heavy lifting (e.g. cleaning-up unused state when components are destroyed, creating new instances of stores when needed etc.)…
resources
- “On The Subject Of Subjects (in RxJS)” by Ben Lesh
- “RxJSRxJS Observables versus Subjects” by Cory Rylan
- StackBlitz example showing the differences among
Observable.from([])
,Subject
andBehaviorSubject