DEV Community

Discussion on: Simple state management in Angular with only Services and RxJS

Collapse
 
avatsaev profile image
Aslan Vatsaev • Edited

BehaviourSubject is not a simple observable, it's an observer AND an observable at the same time that can give you its latest state synchronously.

You're already sharing the same observable because it's assigned to a public readonly property

That doesn't mean the observer is shared, and that doesn't change the fact that when someone subscribes to todos$, a new dedicated observer will be created for it. A shared observable means that all subscribers are getting their data stream from a single observable source. (lookup rxjs multicasting)

More info here: learnrxjs.io/operators/multicastin...

Also, why not just use a ReplaySubject if you need the previous value? You lose getValue...

I need to be able to get the previous state synchronously in the reducers, as I already explained in my other comment, reducers are synchronous functions that take previous state and reduce it to a new state in an immutable way.

The reason we need the replay part is because some components might be rendered asynchronously (after fetching some data from api for ex), and might miss the emits in todos$ observable, so when they subscribe to it they won't know what happened in the source before component came to life, the replay will emit the latest value to all observers upon subscription.

On the other hand, the second share replay is not necessary, I updated the code.

Hope I answered your questions.