Creating an Observable with Angular — Part II: the 4 different types.

Not everybody is aware of the different types of Observable we can use in Angular. In my previous article Creating an Observable with Angular — Part I: a basic example, I explained how to create a basic Observable. If you are not familiar with Observable, Subject and Subscription, I suggest you read this first article before you continue.

Today, I would like to go through the 4 types of Subject that RxJS provides us with to create an Observable, namely:

  • Subject
  • BehaviorSubject
  • ReplaySubject
  • AsyncSubject

The main difference between them is how they react to subscribe().

Subject

When you subscribe to a Subject, you get every event that this Subject emits after you have subscribed (including complete) as shown on the figure.

With a Subject, the Observer will never be notified of events 1 and 2.

To see it in action, here is a small video:

BehaviorSubject

A BehaviorSubject behaves like a Subject, except the Observer also receives the last event that occurred before the subscription. It then receives all the events occurring after the subscription, like for a regular Subject.

In this case, the Observer will be notified about event 2 when it subscribes, but not about event 1.

ReplaySubject

With a ReplaySubject, the Observer receives all past events when it subscribes. It then receives all the events occurring after the subscription, like for a regular Subject.

The Observer will know all the previous events, that is to say events 1 and 2.

AsyncSubject

This one has a peculiar behavior. AsyncSubject will wait for complete to emit the last event and then the complete event.

So, the Observer will only be notified about event 4 (and complete).

I hope this short article will help you use the different types of Subject according to your needs. You can find the code here ;)