DEV Community

Cover image for RxJS Deep Dive: Exploring BehaviorSubject with Angular
vetriselvan Panneerselvam
vetriselvan Panneerselvam

Posted on

RxJS Deep Dive: Exploring BehaviorSubject with Angular

Hey Devs! 👋

We’re back with another weekly RxJS exploration — and this time, we're diving into a widely used and incredibly useful concept: the BehaviorSubject.

Ever needed to grab the last emitted value even after you’ve subscribed late? That's exactly what BehaviorSubject was made for.

Let's walk through what makes it special, how to use it, and explore it with an interactive Angular example.

💭 Why Use BehaviorSubject?

A BehaviorSubject is a type of Subject with a twist:

  • ✅ It always holds the latest value.
  • ✅ When a new observer subscribes, it immediately receives the current value.

This makes it perfect for state management and reactive programming in Angular.

🔔 Note: You must provide an initial value when creating a BehaviorSubject.

🛠️ Angular Example — BehaviorSubject in Action

We’ll build a simple UI where you can:

  1. Send new values to the BehaviorSubject.
  2. Add observers dynamically and watch how they immediately receive the latest value.

🧩 HTML Template

<h3>BehaviorSubject</h3>

<div class="text-wrapper">
  <div class="text">
    <textarea
      class="textarea-modern"
      [(ngModel)]="behaviorSubjectText"
      id="behaviorSubject"
    ></textarea>
    <div class="btn-container">
      <button class="btn-ghost" (click)="sendBehaviorSubject()">Send</button>
      <button class="btn-ghost" (click)="addBehaviorSubject()">Add Observer</button>
    </div>
  </div>

  <div class="example">
    @for (item of behaviorSubjectArray(); track $index) {
      @let data = behaviorSubject | async;
      <div class="card">
        <div class="index">{{$index}}</div>
        <div class="data">{{data | json}}</div>
      </div>
    }
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

⚙️ Component Code (TypeScript)

import { Component, model, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'app-rxjs-operator',
  imports: [CommonModule, FormsModule],
  templateUrl: './rxjs-operator.html',
  styleUrl: './rxjs-operator.scss',
})
export class RxjsOperator {
  behaviorSubject = new BehaviorSubject('Hello this is BehaviorSubject!');
  behaviorSubjectArray = signal<number[]>([0]);
  behaviorSubjectText = model<string>('');

  sendBehaviorSubject() {
    this.behaviorSubject.next(this.behaviorSubjectText());
  }

  addBehaviorSubject() {
    this.behaviorSubjectArray.update((prev) => [...prev, 1]);
  }
}
Enter fullscreen mode Exit fullscreen mode

🧪 What Happens When...

✅ Case 1: Initial Value

When the component loads, the BehaviorSubject emits its initial value:

Hello this is BehaviorSubject!
Enter fullscreen mode Exit fullscreen mode

Any existing or newly added observers will instantly receive this value.

Image description


✏️ Case 2: Sending New Values

When a user types a message and hits Send, the value is pushed using next():

this.behaviorSubject.next(this.behaviorSubjectText());
Enter fullscreen mode Exit fullscreen mode

All current observers get this new value immediately.

Image description

🧙‍♂️ Case 3: Adding New Observers

Clicking Add Observer adds a new subscription. Unlike a regular Subject, the new observer doesn't wait for a new value — it gets the most recent value right away. ✨

This is what makes BehaviorSubject so powerful in Angular UI data flows!

Image description

🔍 Behind the Scenes: What’s in BehaviorSubject?

Let’s peek under the hood:

export class BehaviorSubject<T> extends Subject<T> {
  constructor(private _value: T) {
    super();
  }

  next(value: T): void {
    super.next((this._value = value));
  }
}
Enter fullscreen mode Exit fullscreen mode

Key points:

  • It extends the Subject class.
  • It stores the last value privately (_value).
  • The next() method updates the internal value and emits it.
  • On subscription, it immediately sends the current value to the new subscriber.

🧠 Summary

Here’s what we learned about BehaviorSubject:

✅ Stores the latest value
✅ Emits to new subscribers immediately
✅ Perfect for reactive state management in Angular
✅ Behaves just like a Subject with added benefits

🧭 What’s Next?

In the next post, we’ll explore another powerful RxJS type: the ReplaySubject — great for replaying multiple past values to new subscribers.

💬 Got questions or use cases you want to share? Drop a comment below! Let's discuss more Angular magic. ✨

✍️ Author: Vetriselvan

👨‍💻 Frontend Developer | 💡 Code Enthusiast | 📚 Lifelong Learner | ✍️ Tech Blogger | 🌍 Freelance Developer

Top comments (0)