Cover image for B is for BehaviorSubject

B is for BehaviorSubject

juliandierkes profile image Julian Dierkes ・1 min read

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:

  1. It has an initial value
  2. 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:

  1. 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.
  2. 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.

Posted on by:

juliandierkes profile

Julian Dierkes


I am a young full stack web developer at bosch connected industry and mainly working with Spring and Angular. In my free time I love making music and enjoy doing all sorts of craftsmanship.


markdown guide