Observable

An observable represents a stream of data that can be observed over a period of time. It helps in asynchronous operations well which helps components to react to the changes by subscribing to it. Late subscribers receive values only after subscription, unlike BehaviorSubject which gets the latest value. These are like immutable which can’t access the previous values before subscription.

Syntax

import { Observable } from 'rxjs';

// Create a regular Observable with no initial value
const myObservable = new Observable<string>(observer => {
  observer.next('Initial Value'); // No initial value, just an example
});

// Subscribe to the Observable
myObservable.subscribe(value => {

  // Handle the received value
});

// Function to emit a new value in the Observable syntax
const emitValue = () => {

  // Trigger the emission of a new value
};

Example: The below program describes the usage of BehaviorSubject and Observable with the help of the same goal. So, we can figure out the difference between them and their work. 

The example is the same as for BehaviorSubject, which involves a button that on clicked updates the value and displays it on the screen. We also have another button to subscribe to Observable. Through this, we demonstrate how values are updated after subscribing to observable.

HTML




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


Javascript




//difference-example.component.ts
import { Component, OnInit } 
    from '@angular/core';
import { Observable } from 'rxjs';
  
@Component({
    selector: 'app-difference-example',
    templateUrl: './difference-example.component.html',
})
export class DifferenceExampleComponent implements OnInit {
    private myObservable = 
        new Observable<string>(observer => {
  
         // No initial value, just an example
        observer.next('Initial Value');
        this.emitValue = () => observer.next(
            `New Value ${Math.floor(Math.random() * 100)}`);
    });
    currentValue!: string;
    observableSubscriptionValue!: string;
      
    // Function to emit a new value
    emitValue!: () => void; 
  
    ngOnInit() {
  
        // Subscribe to the Observable
        this.myObservable.subscribe(value => {
            this.currentValue = value;
        });
    }
  
    updateValue() {
  
        // Update the value of the Observable
        this.emitValue();
    }
  
    delayedSubscribeToObservable() {
  
        // Delayed subscription to Observable
        setTimeout(() => {
            this.myObservable.subscribe(value => {
  
                // Update value for display in HTML
                this.observableSubscriptionValue = value; 
            });
        }, 1000); // Delayed subscription after 1 sec
    }
}


Output: As you can observe through the above example, the updated value just updates the value then after subscribing to Observable the values are not initialized and started from a new initial state unlike BehaviorSubject which is initialized with the latest value.

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

...