ReplaySubject, BehaviorSubject & AsyncSubject In Angular

ReplaySubject, BehaviorSubject & AsyncSubject In Angular

In Angular, there are three types of subjects: replaySubject, behaviorSubject, and asyncSubject. In this article, we will learn what they are, how they function, and how to use them in Angular.

BehaviorSubject

BehaviorSubject needs an initial value, then stores and emits the current value to new subscribers.

import { Component, VERSION } from "@angular/core";
import { BehaviorSubject, Subject } from "rxjs";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  subject$ = new BehaviorSubject("0");
 
  ngOnInit() {
    this.subject$.subscribe(val => {
      console.log("Sub1 " + val);
    });
 
    this.subject$.next("1");
    this.subject$.next("2");
 
    this.subject$.subscribe(val => {
      console.log("sub2 " + val);
    });
 
    this.subject$.next("3");
    this.subject$.complete();
  }
}
 
 
 
***Result***
 
Sub1 0
Sub1 1
Sub1 2
sub2 2
Sub1 3
sub2 3

We establish a new BehaviorSubject and give it a starting value, often known as a seed value. The original value is saved in the BehaviorSubject.

subject$ = new BehaviorSubject("0");

The BehaviorSubject emits the stored value as soon as the first subscriber subscribes to it. i.e. 0

this.subject$.subscribe(val => {
  console.log("Sub1 " + val);
});

Two more values are emitted. The BehaviorSubject saves the most recent value emitted, which is 2 in this case.

this.subject$.next("1");
this.subject$.next("2");

Subscriber2 is now a subscriber to it. It obtains the most recent value stored, which is 2 right away.

this.subject$.subscribe(val => {
  console.log("sub2 " + val);
});

ReplaySubject

When new subscribers first subscribe, ReplaySubject replays old values to them.

Every value that the ReplaySubject emits will be stored in a buffer. It will send them to new subscribers in the sequence in which they were received. The options bufferSize and windowTime can be used to customize the buffer.

bufferSize: ReplaySubject will hold a certain number of things in its buffer. It's set to infinite by default.

windowTime: The amount of time the value will be kept in the buffer. Infinity is the default value.

Example

import { Component, VERSION } from "@angular/core";
import { ReplaySubject, Subject } from "rxjs";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  subject$ = new ReplaySubject();
 
  ngOnInit() {
    this.subject$.next("1");
    this.subject$.next("2");
 
    this.subject$.subscribe(
      val => console.log("Sub1 " + val),
      err => console.error("Sub1 " + err),
      () => console.log("Sub1 Complete")
    );
 
    this.subject$.next("3");
    this.subject$.next("4");
 
    this.subject$.subscribe(val => {
      console.log("sub2 " + val);
    });
 
    this.subject$.next("5");
    this.subject$.complete();
 
    this.subject$.error("err");
    this.subject$.next("6");
 
    this.subject$.subscribe(
      val => {
        console.log("sub3 " + val);
      },
      err => console.error("sub3 " + err),
      () => console.log("Complete")
    );
  }
}
 
***Result***
Sub1 1
Sub1 2
Sub1 3
Sub1 4
sub2 1
sub2 2
sub2 3
sub2 4
Sub1 5
sub2 5
Sub1 Complete
sub3 1
sub3 2
sub3 3
sub3 4
sub3 5
sub3 err

We begin by creating a ReplaySubject.

subject$ = new ReplaySubject();

Two values are emitted by ReplaySubject. These will be saved in a buffer as well.

this.subject$.next("1");
this.subject$.next("2");

It is something to which we subscribe. From the buffer, the observer will receive 1 and 2.

this.subject$.subscribe(
  val => console.log("Sub1 " + val),
  err => console.error("Sub1 " + err),
  () => console.log("Sub1 Complete")
);

After emitting two additional values, we resubscribe. All prior values will be sent to the new subscriber as well.

this.subject$.next("3");
this.subject$.next("4");

this.subject$.subscribe(val => {
  console.log("sub2 " + val);
});

We add one more value and are finished. All subscribers will receive the entire package. They will no longer receive any notifications or values.

this.subject$.next("5");
this.subject$.complete();

We now send an error message as well as a value. Previous subscribers will not see this because their accounts have been closed.

this.subject$.error("err");
this.subject$.next("6");

We are now re-subscribing. All of the values up to Complete will be sent to the subscriber. However, instead of receiving the Complete notice, it will receive an Error notification.

this.subject$.subscribe(
     val => {
       console.log("sub3 " + val);
     },
     err => console.error("sub3 " + err),
     () => console.log("Complete")
   );

AsyncSubject

When AsyncSubject completes, it only transmits the most recent value. If it fails, it will display an error message but not any values.

import { Component, VERSION } from "@angular/core";
import { AsyncSubject, Subject } from "rxjs";
 
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  subject$ = new AsyncSubject();
 
  ngOnInit() {
    this.subject$.next("1");
    this.subject$.next("2");
 
    this.subject$.subscribe(
      val => console.log("Sub1 " + val),
      err => console.error("Sub1 " + err),
      () => console.log("Sub1 Complete")
    );
 
    this.subject$.next("3");
    this.subject$.next("4");
 
    this.subject$.subscribe(val => {
      console.log("sub2 " + val);
    });
 
    this.subject$.next("5");
    this.subject$.complete();
 
    this.subject$.error("err");
 
    this.subject$.next("6");
 
    this.subject$.subscribe(
      val => console.log("Sub3 " + val),
      err => console.error("sub3 " + err),
      () => console.log("Sub3 Complete")
    );
  }
}
 
 
**Result **
Sub1 5
sub2 5
Sub1 Complete
Sub3 5
Sub3 Complete

In the example above, all subscribers, even those who subscribe after the event has ended, will receive the amount 5.

However, if the AsyncSubject fails, all subscribers will receive an error message with no value.

Conclusion

In this article, we learned what is ReplaySubject, BehaviorSubject & AsyncSubject and how to use them in Angular.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post