Development

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

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));

subject.next(1);    
// Output: 1

subject.next(2);    
// Output: 2

subject.complete();
// Subject is no longer "active"

subject.next(3);    
// Output: silently ignored

BehaviorSubject

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

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);
replaySubject$.next(1);
replaySubject$.next(2);
replaySubject$.next(3);

replaySubject$.subscribe(console.log);
// Output: 3

AsyncSubject

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();
asyncSubject$.next(1);
asyncSubject$.next(2);
asyncSubject$.next(3);

asyncSubject$.subscribe(console.log);
// Nothing happens

asyncSubject$.complete();
// Output: 3

Conclusion

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