Understanding Subject, BehaviorSubject, ReplaySubject

Subject is a special observable that acts as both observer & observable. It'll allow to emit new value using next() method. It allows value to be multicasted to many observers. Which means, all the subscribers, who subscribe to the subject will receive the same instance of the subject and the same value emitted. It is also called as hot observable which does not wait for subscriber to emit value. It can start emitting value right after the use of next() method.

It plays a vital role in communication between two components and transferring data. But there is a problem, when you subscribe to an event that is already emitted then you'll not get any data. The emitted data will be lost. Let's see it in detail:

Subject is emitted and subscribed as depicted in the image above. But, what will happen here is nothing. Yes, when we subscribe a subject which has already emitted a value then no value will be received as it is already emitted and is lost.

So, what can be the solution for this?

Well, this can be handled using BehaviorSubject or ReplaySubject. BehaviourSubject and ReplaySubject works mostly in a similar way with slight differences.

  • BehaviorSubject can hold only last data emitted in the memory whereas ReplaySubject can hold in memory as much as we define in the bufferSize. By default the bufferSize is infinite.

In the image below, we have instantiated ReplaySubject with default bufferSize which is Infinite.

But we can also limit the bufferSize by passing a constructor parameter as depicted in the image below.

  • BehaviourSubject needs an initial value but ReplaySubject does not need any initial value.

If you do not provide an argument value then it prompt an error. It is mandatory to provide an argument value for BehaviorSubject.

So, which one to use between BehaviorSubject and ReplaySubject if there is no initial value?

We can use ReplaySubject if we have got no initial value and by passing a constructor parameter 1.


Similar Articles