0
0
AngularConceptBeginner · 3 min read

What is BehaviorSubject in RxJS: Explanation and Example

BehaviorSubject in RxJS is a special type of observable that stores the latest value and emits it immediately to new subscribers. It allows you to get the current value anytime and keeps emitting new values to all subscribers as they come.
⚙️

How It Works

Imagine a BehaviorSubject as a live radio station that always plays the latest song. When you tune in (subscribe), you immediately hear the current song playing, not just the songs that will play in the future. This means it remembers the last value it emitted and shares it right away with anyone new joining.

In technical terms, BehaviorSubject holds a current value internally. When you subscribe, it sends this current value immediately. Then, whenever a new value is added, it broadcasts that to all subscribers. This makes it different from a regular observable that only sends values after you subscribe.

💻

Example

This example shows how BehaviorSubject emits the current value immediately to new subscribers and updates all subscribers when a new value is emitted.

typescript
import { BehaviorSubject } from 'rxjs';

const subject = new BehaviorSubject('Initial');

// First subscriber
subject.subscribe(value => console.log('Subscriber 1:', value));

// Emit new value
subject.next('Second');

// Second subscriber subscribes after new value
subject.subscribe(value => console.log('Subscriber 2:', value));

// Emit another value
subject.next('Third');
Output
Subscriber 1: Initial Subscriber 1: Second Subscriber 2: Second Subscriber 1: Third Subscriber 2: Third
🎯

When to Use

Use BehaviorSubject when you need to keep track of the latest value and share it with multiple parts of your app. For example, it is great for managing user authentication status, form state, or any data that changes over time but should be immediately available to new subscribers.

It is especially useful in Angular services to share data reactively between components without losing the current state.

Key Points

  • Stores the latest value: New subscribers get the current value immediately.
  • Multicasts values: All subscribers receive updates.
  • Useful for state management: Keeps and shares state reactively.
  • Part of RxJS library: Works well with Angular's reactive programming.

Key Takeaways

BehaviorSubject holds and emits the latest value immediately to new subscribers.
It is ideal for sharing state or data that changes over time across multiple parts of an app.
Use BehaviorSubject in Angular services to keep components in sync reactively.
Unlike regular observables, BehaviorSubject always has a current value available.
It broadcasts new values to all subscribers as soon as they are emitted.