DEV Community

Cover image for B is for BehaviorSubject
Julian Dierkes
Julian Dierkes

Posted on

1

B is for BehaviorSubject

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️