Understanding RxJS Subjects and their use

2 min. read

When it comes to subjects, school subjects are commonly thought of -- math, reading, science. However, in the world of JavaScript, an RxJS Subject is something else entirely.

What is a Subject?

An RxJS Subject is a special type of observable and is also an observer. It is used for controlling data used and received on reactive websites.

An observable produces values over time and allows handling of various asynchronous streams of data, while an observer listens for the values emitted by an observable.

Why are Subjects important?

Subjects can be used to handle incoming changes in data for a faster, more accurate web application. The usage of subjects can seamlessly provide a greater experience for end users by noticeably enhancing the site's performance.

Different Types of Subjects


Subject has no initial value and does not return the current value on Subscription. It triggers only on .next(value) call and return/output the value. Subject is multicast, meaning it is able to emit its values to multiple Observers.

const subject = new Subject();
subject.subscribe(x => console.log(x));;    
// Output: 1;    
// Output: 2

// Subject is no longer "active";    
// Output: silently ignored


BehaviorSubject is similar to a Subject. The difference is a BehaviorSubject will return the initial value or the current value on Subscription, while a Subject does not.


ReplaySubject emits old values to new subscribers. First argument passed into ReplaySubject determines the number of values (last emitted) that new/late subscribers will receive and can set max time old values are available.

The figure below shows ReplaySubject emitting value with no subscribers and then with a subscriber.

const replaySubject$ = new ReplaySubject(1);

// Output: 3


AsyncSubject does not emit any values to subscribers until completion; it does not emit values on .next(), and they only emit 1 single value (last value received on completion).

In the following example, AsyncSubject is used and shows nothing happens until complete() is called.

const asyncSubject$ = new AsyncSubject();

// Nothing happens

// Output: 3


We hope you learned something new and are inspired to create something after reading this article. Consider subscribing to our blog at the bottom of this page for more updates and technical articles.

If you have any questions or comments, we'd love to hear from you.

Kim Pham

Senior Front-end Web Developer