All you need to know about Async Subject

Satyapriya Mishra
2 min readAug 12, 2020

AsyncSubject is a variant of Subject where only the last value of the Observable execution is sent to its observers, and only when the execution is complete. Until the Observable is complete, there will not be any value subscribed to the subscribers.

The asyncSubject is a very good candidate for network requests through GET or fetch API where only one value is expected.

A simple demonstration of the asyncSubject is given below.

import { AsyncSubject } from 'rxjs' ;const as$ = new AsyncSubject(); // (1)as$.subscribe((data) => { // (2)console.log( 'Subscriber A: ' + data);});as$.next(Math.random()); // (3)as$.complete(); // (4)as$.subscribe((data) => {console.log( 'Subscriber B: ' + data);});as$.next(Math.random());as$.next(Math.random());as$.complete();

Let’s check what is happening in each of the steps in the above code snippet.

In step1, we create a new asyncSubject through the constant as$. Then in step2, we subscribe to the asyncSubject created in the previous step. Then we assign a new value to the asyncSubject with the next() operator and then we complete it. We repeat the same steps for creating a new subscriber called B.

Now first let’s see the output for the above code snippet.

// Subscriber A: 0.38896475571548295// Subscriber B: 0.38896475571548295

In the output we can see two random numbers which are coming from the next() methods as we had implemented in the above snippet.

Here one thing to observe is that, even if we have called the next() method twice for the subscriber B, we are getting only one value printed. This essentially means that the subscriber got only one value from the source and it got the value when the source asyncSubject was completed. That is the reason that we got only one value for both the subscribers. That is the reason why asyncSubject is an ideal candidate for fetch api calls.

--

--