DEV Community

Cover image for A is for AsyncSubject
Julian Dierkes
Julian Dierkes

Posted on

A is for AsyncSubject

The AsyncSubject is a lesser known sub class of Subject, that emits only its last value to its Observers once (and only if) it completes.

But isn't that the same thing as using a Subject and the last operator?

Nearly, but the AsyncSubject is designed for multicast usage (multiple Observers) and the behavior differs for Observers that subscribe after completion.
The value is also emitted to Observers subscribing after the AsyncSubject has already completed, which does not happen when using a simple Subject.

When would I need such a Subject?

For example this could be handy for implementing something containing HTTP requests. Knowing that http request will only have a single result it totally makes sense to use an AsyncSubject because:

  1. It will only emit a single value
  2. It completes, so there is no need for the Observers to unsubscribe
  3. Other Observers can even subscribe after the request has finished

Top comments (0)