Subjects in RxJS

What is a Subject?

A subject is a producer and a consumer both in RxJS. It can act as an observer as well as an observable. It can hold data as well as emit the data at the same time.  A subject can multicast to multiple observers whereas observables are unicast. The subject is also called a different multicast observable which can do multicasting to the subscribers of the object.
  • The subject implements the observer interface. So it has methods like next(), error(), complete() and unsubscribe().
  • The subject has a list of observers.
  • The subject can be an observer or an observable. We can make the subject an observer and pass it to an observable to subscribe.

Making Subject Instance

We can create a new instance for a subject using the Rx.Subject() method.

const sub = new Rx.Subject();

We can push data into our subject using the next() method.

sub.next("Hello World");

The subject will have a list of subscriptions. So this data will be sent to all using the next() method.

Example

const sub = new Rx.Subject();
sub.next(1); 
sub.next(2);
const subscription = sub.subscribe(a => {
  console.log('Value from subscription:', a);
});
sub.next(4); 

The output is shown below:

Value from subscription:4

The value printer in the console will be 4. After we subscribe to the subject, only those values will be shown. After subscribing to our subject, we have pushed 4.

Handling Errors With Subjects

We can use the error() method of the observer interface to show any errors. 

const sub = new Rx.Subject();

const subscription = sub.subscribe(a => {
  console.log('Value from subscription:', a);
});

sub.error(new Error('Subscription got some error'));

Multicasting Using Subject

The main significance of the subject is that it multicasts. We can use it as a multicast observable which will send the data to all the subscribers. A subject can have multiple observers that can be passed to an observable. If we emit that observable the data will be sent to all the subscribers of that subject. 

const sub = new Subject();

const obs= new Observable(function subscribe(subscriber) {
 setTimeout(() => {
    subscriber.next(1)
  }, 500);
});

const subscription = sub.subscribe(a => {
  console.log(a);
});

const subscriptionNew = sub.subscribe(x => {
  console.log(x);
});

sub.next("Hello RxJS Subject");
obs.subscribe(sub);


The output of this is below:

Hello RxJS Subject
Hello RxJS Subject
1
1

Comments