RxJS Subjects Explained with Examples

An explanation of subjects in RxJS and an examples of the 4 different types

Photo by Nolan Issac on Unsplash

In this article, I will explain the 4 types of subjects in RxJS and when to use each with examples.

Subject BehaviorSubject RelaySubject AsyncSubject

For more content like this, check out https://betterfullstack.com

Subject

An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers .

A Subject is like an Observable , but can multicast to many Observers . Subjects are like EventEmitters : they maintain a registry of many listeners.

Every Subject is an Observable .

Every Subject is an Observer .

A Subject sends data to subscribed observers. Any previously emitted data is not sent to new observers.

BehaviorSubject

BehaviorSubject stores the latest value emitted to its consumers, and whenever a new Observer subscribes, it will immediately receive the “current value”.

BehaviorSubjects are useful for representing “values over time”. For instance, an event stream of birthdays is a Subject , but the stream of a person’s age would be a BehaviorSubject .

Send the last data to new observers.

RelaySubject

A ReplaySubject is similar to a BehaviorSubject in that it can send old values to new subscribers, but it can also record a part of the Observable execution.

A ReplaySubject records multiple values from the Observable execution and replays them to new subscribers.

Previously sent data can be “replayed” to a new observer.

AsyncSubject

A AsyncSubject will emit the last value to observers when the sequence is completed.

Summary

An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers .

In addition, we have 3 special subjects which are BehaviorSubject , RelaySubject , and AsyncSubject . They behave differently in how observers receive data.

I hope you found this article useful! You can follow me on Medium. I am also on Twitter. Feel free to leave any questions in the comments below. I’ll be glad to help out!

Resources / References

[1]: Subject https://rxjs-dev.firebaseapp.com/guide/subject