Types of Subjects in RxJS

Miguel Angel Muñoz
Version 1
Published in
2 min readSep 14, 2022
Photo by Tracy Adams on Unsplash

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 an Observable. Given a Subject, you can subscribe to it, providing an Observer, which will start receiving values normally.
  • Every Subject is an Observer. To send a new value to the Subject, just call next(value), and it will be multicasted to the observers registered to listen to the Subject.

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.

Subject Marble Diagram
Subject Marble Diagram
Subject Coding Example

BehaviorSubject

A BehaviorSubject behaves like a Subject, but the Observer also receives the last value emitted before the subscription was made.

BehaviorSubject Marble Diagram
BehaviorSubject Coding Example

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:

ReplaySubject(2) Marble Diagram
ReplaySubject(2) Coding Example

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.

--

--

Miguel Angel Muñoz
Version 1

Principal Software Engineer @ Version 1. Front-end/Javascript enthusiast 💻 & Video Game lover 🎮 . I spend my free time learning 📝 or playing 👾.