Types of Subjects in RxJS
If you're reading this, you've probably been playing with the different types of subjects that RxJS offers. But, do you know why you are specifically using each one? Or more importantly, are you using the one that you really need?
Let's take a closer look at the four different types available in RxJS:
Subject
BehaviorSubject
ReplaySubject
AsyncSubject
Subject
A Subject
is a special type of Observable that allows values to be multicasted to many observers.
- Every
Subject
is anObservable
. Given aSubject
, you cansubscribe
to it, providing anObserver
, which will start receiving values normally. - Every
Subject
is anObserver
. To send a new value to theSubject
, just callnext(value)
, and it will be multicasted to the observers registered to listen to theSubject
.
When you subscribe to a Subject
, the Observer
will receive every value emitted after the subscription was made. Any values emitted before the subscription won't be received by the Observer
.
BehaviorSubject
A BehaviorSubject
behaves like a Subject
, but the Observer
also receives the last value emitted before the subscription was made.
ReplaySubject
A ReplaySubject
behaves like a BehaviorSubject
, but instead of only emitting the last value, you can record multiple values to replay them to new subscribers. For example, you can buffer the last 2 values:
AsyncSubject
The AsyncSubject
has different behaviour. It's a variant where only the last value of the Observable
execution is sent to its observers, and only when the execution completes.
I hope you find this article useful. Now review your code to check if you're using the best one to suit your needs!
About the author:
Miguel Munoz is a Principal Software Engineer here at Version 1.