BehaviorSubject

BehaviorSubject is a concept in the RxJS library that is an extension of observable. This not only provides a stream of data but maintains the most recent value or latest value to subscribers. It acts as both observer and observable. Here when a late subscriber arrives, they immediately receive the latest value present. This is an advantage to BehaviorSubject when the current state is crucial, and subscribers need to access values immediately to the latest emitted value.

Syntax

import { BehaviorSubject } from 'rxjs';

// Create a BehaviorSubject with an initial value
const myBehaviorSubject = new BehaviorSubject<string>('Initial Value');

// Subscribe to the BehaviorSubject
myBehaviorSubject.subscribe(value => {

  // Handle the received value
});

// Update the value of the BehaviorSubject
myBehaviorSubject.next('New Value');

Example: This example involves a button when clicked updates the value and displays on the screen. We also have another button to subscribe to BehaviorSubject. Through this, we demonstrate how values are updated after subscribing to BehaviorSubject.

HTML




<!--difference-example.component.html-->
<div>
    <p>Current Value: {{ currentValue }}</p>
    <button (click)="updateValue()">
          Update Value
      </button>
    <button (click)="delayedSubscribeToBehaviorSubject()">
          Subscribe to BehaviorSubject
      </button>
    <div *ngIf="behaviorSubjectSubscriptionValue">
        <p>
              Subscribed to BehaviorSubject: 
            {{ behaviorSubjectSubscriptionValue }}
          </p>
    </div>
</div>


Javascript




//difference-example.component.ts
import { Component, OnInit } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
  
@Component({
    selector: 'app-difference-example',
    templateUrl: './difference-example.component.html',
})
export class DifferenceExampleComponent implements OnInit {
    private myBehaviorSubject = 
        new BehaviorSubject<string>('Initial Value');
  
    currentValue!: string;
    behaviorSubjectSubscriptionValue!: string;
  
    ngOnInit() {
      
        // Subscribe to the BehaviorSubject
        this.myBehaviorSubject.subscribe(value => {
            this.currentValue = value;
        });
    }
  
    updateValue() {
      
        // Update the value of the 
        // BehaviorSubject and Observable
        const newValue =
            `New Value ${Math.floor(Math.random() * 100)}`;
        this.myBehaviorSubject.next(newValue);
    }
  
    delayedSubscribeToBehaviorSubject() {
      
        // Delayed subscription to BehaviorSubject
        setTimeout(() => {
            this.myBehaviorSubject.subscribe(value => {
  
                // Update value for display in HTML
                this.behaviorSubjectSubscriptionValue = value; 
            });
        }, 1000); // Delayed subscription after 1 second
    }
}


Output: As you can observe through the above example, the updated value just updates the value then after subscribing to BehaviorSubject, the values are initialized from the latest value and are updated the same.

What is the Difference Between BehaviorSubject and Observable in Angular ?

Angular being a powerful framework offers various features and tools. One such powerful feature is to handle asynchronous operations by implementing the BehaviorSubject and Observable, which are the key components of the RxJS library. It also helps to manage the flow of data reactively. This article covers the basics of BehaviorSubject and Observable in Angular, along with understanding their basic implementation, & the differences between them.

Table of Content

  • BehaviorSubject
  • Observable
  • Difference between BehaviorSubject and Observable

Similar Reads

BehaviorSubject

BehaviorSubject is a concept in the RxJS library that is an extension of observable. This not only provides a stream of data but maintains the most recent value or latest value to subscribers. It acts as both observer and observable. Here when a late subscriber arrives, they immediately receive the latest value present. This is an advantage to BehaviorSubject when the current state is crucial, and subscribers need to access values immediately to the latest emitted value....

Observable

...

Difference between BehaviorSubject and Observable

...