Table of contents
No headings in the article.
In this article, I will explain the types of RxJS subjects with examples.
There are 4 types of RxJS subjects:
Subject
BehaviorSubject
AsyncSubject
RelaySubject
Subject in RxJS is special hybrid which acts as observer and observable both. This way data can be pushed to the subject and the subject's subscriber in turn gets the pushed value.
Subject is multicasting, using one subject one value can be multicasted to many subscribers. The subject is the way of sharing data between unrelated components.
Using Subject: Create a subject always starts by creating the instance of RxJS Subject:
sub = new Subject();
Multiple subscriptions can be created and internally the subject will keep a list of subscriptions:
const subscription1 = sub.subscribe(x => console.log(`${x} ${x}`));
const subscription2 = sub.subscribe(x => console.log(x.toUpperCase()));
Data can be pushed into the subject using its next
method:
sub.next('Next Value Pushed');
BehvaiorSubject - BehvaiorSubject always contains a default value which we pass at the time of declaring BevaiorSubject. and it emits current value to new subscribers.
sub = new BehaviorSubject('Hello');
ReplaySubject - It emits old values to new subscribers, even if they subscribe after the values are sent. However, it consumes more memory as it stores multiple previous values depending upon how it is configured.
const sub = new ReplaySubject(3);
Here 3 is the no of the previous value you want to emit to new subscribers.
AsyncObject - AsyncObject is a variant of Subject where only the last value of the observable to sent to its observer only when the observable marks its completion. Until the observable is complete there will be no value delivered to the observer.
const sub = new AsyncSubject();
sub.next(1)
sub.subscribe((data) => console.log(data)) // nothing logged
sub.next(2)
sub.subscribe((data) => console.log(data)) // again nothing logged
sub.complete(); // 1, 2 logged by both subscriber
Conclusion - So here it was about all the RxJS subjects. We have 4 types of subjects.
Subject - No initial value or replay.
BehaviorSubject - Requires initial value and emits a current value.
ReplaySubject - Replays old emitted values to new subscribers.
AsyncSubject - Emits value only when observable is completed.
Happy Learning