LiveLoveApp logo

AsyncSubject

AsyncSubject

The AsyncSubject class extends the Subject class, which extends the Observable class. The AsyncSubject emits the last value, and only the last value, to all Observers upon completion.

Example

Let's take a look at an example of using the AsyncSubject. As you examine the following code, pay close attention to the order of the Observers and the production of the values.

import { AsyncSubject } from 'rxjs';

/* create an instance of AsyncSubject. */
const asyncSubject = new AsyncSubject<number>();

/* Subscribe to subject. */
asyncSubject.subscribe({
  next: (value) => console.log('before:', value),
  error: console.error,
  complete: () => console.log('complete before')
});

/* Emit some values. */
asyncSubject.next(1);
asyncSubject.next(2);
asyncSubject.next(3);

/* Subscribe late to subject. */
asyncSubject.subscribe({
  next: (value) => console.log('after:', value),
  error: console.error,
  complete: () => console.log('complete after')
});

/*
 * Complete the observable stream.
 * If we do not complete, the AsyncSubject will never emit a next notification.
 */
asyncSubject.complete();

See example on codesandbox

Now, let's break this down:

  1. First, we create a new AsyncSubject instance using JavaScript's native new operator, specifying the generic number type.
  2. We then subscribe to the asyncSubject. We'll log out the string "before" so that we can note that this console log is coming from the Observer before the values are produced via the next() method on the AsyncSubject instance. We'll also pass any errors to the console.error function, and log out "complete before" when the AsyncSubject is complete.
  3. Next, we emit three next notifications. Note that the number 3 is the last value that is emitted.
  4. We then subscribe late, in other words, we subscribe after the next notifications were produced. Perhaps a better way to put it is this Observer has shown up late to the party. If this was not an AsyncSubject and just an Observable then this Observer would not receive any next notifications. Back to our party analogy, the party is over, so the late Observer does not get any cake.
  5. Finally, we invoke the complete() method to signal completion of the AsyncSubject.

Takeaway

The AsyncSubject can be used to notify all Observers of the last next notification upon completion.