Search⌘ K
AI Features

AsyncSubject of RxJS

Explore how AsyncSubject in RxJS emits only the last value after a sequence completes and caches it for all future subscribers. Understand its use in scenarios like HTTP requests to avoid repeated network calls and see how it can act similarly to promises, enabling efficient data handling in reactive programming.

AsyncSubject emits the last value of a sequence only if the sequence is complete. This value is then cached forever, and any Observer that subscribes after the value has been emitted will receive it right away. The AsyncSubject is convenient for asynchronous operations that return a single value, such as Ajax requests.

Let’s see a simple example of an AsyncSubject subscribing to a range:

const Rx = require('rx');
var delayedRange = Rx.Observable.range(0, 5).delay(1000);
var subject = new Rx.AsyncSubject();
delayedRange.subscribe(subject);
subject.subscribe(
  function onNext(item) {
    console.log('Value:', item);
  },
  function onError(err) {
    console.log('Error:', err);
  },
  function onCompleted() {
    console.log('Completed.');
  }
);
AsyncSubject subscribing to the range operator

In the example given above, delayedRange emits the values 0 to 4 after a delay of one second. Then we create a new AsyncSubject subject and subscribe it to the delayedRange ...