Subject and BehaviorSubject - RXJS

Subject and BehaviorSubject - RXJS

In this tutorial, we will learn about the subject and  BehaviorSubject of RXJS.

What is a Subject?

 A Subject is a particular type of Observable from the RxJS library.

The subject is mostly used for cross-component data share/Communication

The subject is a special type of observable because subject works as observable and observer also.

We can do gloabaly data communication using subject

The subject is Multicasting observable means we will get data from when we subscribed not previous data.

A subject has three methods which you can use.

  • subscribe() : with this method, you can activate the subscription of a new subscriber.
  • next():  with this method, you can pass new values. All the current subscribers will receive this.
  • complete(): with this method, you close all the subscriptions to the Subject

Also note that a Subject doesn't have an initial value. Every value passed with the next method will send the values to all the subscribers.

Example:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class DataService {

  username = new Subject <string>("Jigar");

  constructor() { }

  updatedDataSelection(data){
    this.username.next(data);
  }
  
}

We can call next and pass in a new value to the Subject.  

 import { Component, OnInit } from "@angular/core";
import { DataService } from "./data.service";

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
})
export class HeaderComponent implements OnInit {
  constructor(private dataService : DataService ) {}

  exclusive = false;

  ngOnInit() {
    this.dataService.username.next('rahul');
  }
  
}

For getting the updated value we can subscriber observable as below:

 import { Component, OnInit } from "@angular/core";
import { DataService } from "./data.service";

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
})
export class HeaderComponent implements OnInit {
  constructor(private dataService : DataService ) {}

  exclusive = false;

  ngOnInit() {
    this.dataService.exclusive.subscribe((res) => {
      console.log(res):
    });
  }
}

When to use:

  When you need multiple subscribers and care that all the subscribers are getting their new values simultaneously, use Subject.  

BehaviorSubject 

A BehaviorSubject a Subject that can emit the current value while Subjects have no concept of current value.

Example:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {

  username = new BehaviorSubject<string>("Jigar");

  constructor() { }

  updatedDataSelection(data){
    this.username.next(data);
  }
  
}

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like

Leave a Comment