Well i think most of you have already heard about the BehaviorSubject. In case you didn't or want a quick refresh keep reading.
The BehaviorSubject, just like the normal Subject, emits values to its Observers, but there are two main differences:
- It has an initial value
- It emits its current value to new subscribers
What is it good for?
State management for example.
Here you mostly want an initial state, notifications for observers on changes and you also want to receive the current state on any later subscription.
Ok... That's all? This is your example?
Fine let's be more practical:
- A data table. You want the data array that its based on to always be defined. Just use the BehaviorSubject with an initial value of [] and fetch or add some data whenever you feel like doing it. Even if the table subscribes after adding/fetching data the table will immediately receive the current state/data.
- A toggle switch. It has an initial value of false so its deactivated. You want to notify several other components about changes. Even components created after the toggle (and therefore subscribing after the toggle state may have changed) will get the current value of the BehaviorSubject.
Top comments (0)