# What is a AsyncSubject in Angular ?

In 
Published 2022-12-03

This tutorial explains to you what a AsyncSubject is in Angular and also provide you with an example.

In Angular, in many cases we need to see the LAST value of a stream when stream complete and in the same time we need to get access to this value to many consumers (subscribers). Each subscriber/ consumer will do different things function on that value(s). In this situation we have to define a AsyncSubject.

When using AsyncSubject, the subscriber can see the LAST value in the stream when stream complete. It might be useful for you to take a look at the following articles as well: Subject in Angular and BehaviorSubject and ReplaySubject in Angular

In order to use this feature, you have to import "AsyncSubject" from 'rxjs' or 'rxjs/AsyncSubject' into the component that use it:

import { AsyncSubject } from 'rxjs';

Here is the code we used for showing AsyncSubject behavior in Angular 4:

/* app.component.ts */
import { Component } from '@angular/core';
import { AsyncSubject } from 'rxjs';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
 
  products = [
    {name:"apples", price:10, onStock:"Y"},
    {name:"bananas", price:5, onStock:"Y"},
    {name:"tomatoes", price:11, onStock:"Y"}
  ];
 
  ngOnInit() {
 
    console.log('AsyncSubject:');
    let subject5 = new AsyncSubject<number>();
    subject5.next(1);
    subject5.next(2);
 
    let subscription51 = subject5.subscribe( var1  => {
       console.log('subscription51 /'+var1+'/');
       }, 
     
      error => {console.log('Could not load artists')},
      () => {  console.log('Completed')}
    );
    console.log('-----------------------------------');
    subject5.next(3);
    subject5.complete();
    console.log('==================================='); 
  } 
}

And here is the result in the browser console: