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.


โœ๏ธ 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.

๐Ÿง™โ€โ™‚๏ธ 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!

๐Ÿ” 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)