BehaviorSubject vs ReplaySubject(1) -beware of edge cases

Wojciech Trawiński
JavaScript everyday
2 min readFeb 9, 2019

--

If it weren’t for edge cases, an instance of the BehaviorSubject would act the same as an object of the ReplaySubject class with a buffer size of one item. However, the edge cases make a difference, which I will cover in this blog post.

According to the official documentation:

  • BehaviorSubject

A variant of Subject that requires an initial value and emits its current value whenever it is subscribed to.

  • ReplaySubject

A variant of Subject that “replays” or emits old values to new subscribers. It buffers a set number of values and will emit those values immediately to any new subscribers in addition to emitting new values to existing subscribers.

Example

Let’s assume that you want to implement a messages service using reactive approach. The contract can be describe with the aid of the following abstract class:

Next, you can implement the service using either the BehaviorSubject or the ReplaySubject:

BehaviorSubject

ReplaySubject

Subject lifecycle

No values pushed

If you use the BehaviorSubject, you can provide an initial value which will be provided to an observer at subscription time. In contrast, there is no way to accomplish it using the ReplaySubject:

Values already pushed

There’s no difference between the two in this lifecycle phase, namely the last emitted value is replayed to an observer upon subscription:

Subject closed

After the complete notification, only the ReplaySubject emits the last value to an observer:

Conclusions

If you want to provide an initial value at subscription time, even if nothing has been pushed to a Subject so far, use the BehaviorSubject. If you want to have the last value replayed to an observer, even if a Subject is already closed, use the ReplaySubject(1).

Live example:

I hope you liked the post and learned something new 👍. If so, please give me some applause 👏

--

--