BehaviorSubject
Requires an initial value and emits the current value to new subscribers
💡 If you want the last emitted value(s) on subscription, but do not need to supply a seed value, check out ReplaySubject instead!
Why use BehaviorSubject
?
BehaviorSubject
?This specialized subject is ideal when you want to maintain and provide a "current value" to subscribers. Think of it as a scoreboard in a basketball game. Even if you join watching in the middle of the game, you'll still see the current score. Similarly, when a new observer subscribes to a BehaviorSubject
, it immediately receives the current value (or the last value that was emitted).
It's important to remember that a BehaviorSubject
requires an initial value upon instantiation. This is where it differs from a regular Subject
which doesn't have an initial value. Picture a newly installed scoreboard – with BehaviorSubject
, you set a starting score, say 0-0. With a regular Subject
, the board remains blank until a point is scored. Subscribers (early or late) of a normal Subject
will not receive emissions until the Subject
emits a value.
Contrasting with ReplaySubject
, while both provide historical values, ReplaySubject
can relay multiple previous values, not just the last one. If the basketball scoreboard could show the last five scores in the match sequence, that'd be akin to ReplaySubject
. ReplaySubject
also does not receive an initial seed value.
In conclusion, if you need to ensure subscribers always get the latest value upon subscription, or you have an initial seed value, BehaviorSubject
is your pick. If you need more historical emissions, consider ReplaySubject
. And if you don't need any history at all, a simple Subject
might be what you're looking for.
Examples
Example 1: Simple BehaviorSubject
( Stackblitz )
Example 2: BehaviorSubject with new subscribers created on mouse clicks
( Stackblitz )
Related Recipes
Additional Resources
BehaviorSubject 📰 - Official docs
BehaviorSubject - In Depth Dev Reference
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/BehaviorSubject.ts
Last updated