RxJS Subject and its variants

Rxjs


SUBJECT

Subject acts as an observable and observer both which do both listen to new notifications and also send/broadcast it to any dedicated component which subscribes to it.

So the first step is to import “subject” in your typescript file.

import { Subject } from "rxjs/Subject";

and now quickly create a Subject with just a simple line code written below:

let newSubject = new Subject();

The next step is to .subscribe to the subject to create an observer:

newsubject.subscribe(

data => console.log('First Observer: '+ data),

err => console.log(err),

() => console.log('Observer Completed')
)

newSubject.next('This method will start emmitting values')

This above method .next will start emitting the value from the observer without this method above statements won’t work.

OUTPUT :
First Observer: This method will start emitting values

And now we will create another observable for making things more interesting and emitting some more values in it.

let secondObserver = newSubject.subscribe(
    data => console.log('Second Observer: '+ data)
)

newSubject.next('Second value is emitted');
newSubject.next('Third Value is emitted');

OUTPUT :
First Observer: This method will start emitting values
Second Observer: Second value is being emitted
Second Observer: Second value is being emitted
First Observer: Third Value is emitted
Second Observer: Third Value is emitted

As we observe in the above output that second observer did not receive the output emitted by first observer i.e ‘This method will start emitting values’  because the second observer is created after the first value emitted by the first observer.

The subject itself comes with the various variations which we will explain briefly below:

1: BehaviorSubject: BehaviorSubject is one of the variants of Subjects, It is usually used to store the current value, i.e whenever any observer subscribes it stores the latest value emitted to its subscriber, it will immediately receive the latest value from the BehaviorSubject.

So the first step is to import “BehaviorSubject” in your typescript file.

import { BehaviorSubject } from "rxjs/BehaviorSubject";

and now we create a BehaviorSubject with a single line of code written below:

let newBehaviorSubject = new BehaviorSubject('BehaviorSubject');

newBehaviorSubject.next('This method will start emmitting values')

newBehaviorSubject.next('Second observer will subscribe')

OUTPUT :
First Observer: BehaviorSubject
First Observer: This method will start emitting values
First Observer: Second Observer will subscribe
Second Observer:Second Observer will subscribe
First Observer: Second Value is emitted
Second Observer: Second Value is emitted

Here in the above example, you can observe that the second observer will receive the latest/last value being emitted.

2: ReplaySubject: Both BehaviorSubject and ReplaySubject are somewhat similar but the only difference is that BehaviorSubject dispatch only the last emitted value, on the other hand, ReplaySubject dispatches the specified number of values to be emitted.

we need to specify the number of values to be dispatched in ReplaySubject argument while creating an instance of ReplaySubject.

So the first step is to import “BehaviorSubject” in your typescript file.

import { ReplaySubject } from "rxjs/ReplaySubject";

and now we create a ReplaySubject with a single line of code written below:

let newReplaySubject = new ReplaySubject(2);
newReplaySubject.next('First message!')
newReplaySubject.next('Second message!!')
newReplaySubject.next('Third message!!!')

OUTPUT :
First Observer: First message!
First Observer: Second message!!
First Observer: Third message!!!
Second Observer: Second message!!
Second Observer: Third message!!!

In the above output, you can see that the second observer receives only the last 2 values being emitted because we pass 2 as a parameter in ReplaySubject while creating.

3: AsyncSubject: AsyncBehavior is another variant of the subjects, where it will send only the last value to emit by the observable, but only after Observable completes its execution, it will not be sent anything if you do not call  .complete() on the subject.

So the first step is to import “AsyncSubject” in your typescript file.

import { AsyncSubject } from "rxjs/AsyncSubject";

and now we create an AsyncSubject with a single line of code written below:

let newAsyncSubject = new AsyncSubject();

newAsyncSubject.subscribe(
data => console.log('AsyncData emitting:' + data),
)

newAsyncSubject.next(1);
newAsyncSubject.next(2);
newAsyncSubject.next(3);
newAsyncSubject.complete();

OUTPUT :
AsyncData emitting: 3

As you can see in the above output it will display only the last value emitted and after that complete() method is called.

Conclusion:
So after reading this blog, you will have a brief understanding of RxJS subject and its various variations.

Thanks For Reading!!!

knoldus-advt-sticker

Written by 

Nitin Arora is Software Consultant at Knoldus Software LLP with 6 months of experience. He has done MCA from Banarsidas Chandiwala Institute of Information technology, Delhi(GGSIPU). He has a graduation degree in BCA from Jamia Hamdard. He has a sound knowledge of various programming languages like C, C++, Java, and scala. Also has a deep interest in frontend development like Html, CSS, Angular, Javascript. He is currently working in frontend technologies like Angular, Html, CSS, Bootstrap and Typescript. He is focused, hardworking, team-oriented member and always exploring new Technologies, His hobbies is to play cricket, volleyball, and do coding.

Leave a Reply

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!