Thursday, February 22, 2018

Difference Between Subject and Observable

Subject is a special kid of observable.

All subscribers to a subject share the same execution of the subject. i.e. when a subject produces data, all of its subscribers will receive the same data. This behavior is different from observables, where each subscription causes an independent execution of the observable.

Ex.

var subject = new Rx.Subject();

// Here the subject is acting like a data producer
// because it is being subscribed to
subject.subscribe(v => console.log('consumer A: ' + v));
subject.subscribe(v => console.log('consumer B: ' + v));

// Create a source of the data, which in our case is an observable
var observable = Rx.Observable.from([0, 1]);

// Here the same subject acs as a data consumer because it
// can subscribe to another observable

observable.subscribe(subject);

/* Prints */
// Consumer A: 0
// Consumer B: 0
// Consumer A: 1
// Consumer B: 1

Here are some point to motice

1. I had to setup my subscriptions before my subject subscribed to the source.
2. Both the consumers logged the same value for v.

The fact that our consumers log the same data implies that the broadcasted data is shared with all the consumers/subscribers. This is unlike observables, where each consumer/subscriber causes the observable function to be re-executed.

Ex of observable

var observable = Rx.Observable.create(function(source) {
  source.next(Math.random());
});

observable.subscribe(v => console.log('consumer A: ' + v));
observable.subscribe(v => console.log('consumer B: ' + v));

/* Prints DIFFERENT values for both consumers */
// consumer A: 0.25707833297857885
// consumer B: 0.8304769607422662

If we want our observable broadcast same value than we have to wrap it in subject as below

var observable = Rx.Observable.create(function(source) {
  source.next(Math.random());
});

var subject = new Rx.Subject();

subject.subscribe(v => console.log('consumer A: ' + v));
subject.subscribe(v => console.log('consumer B: ' + v));

observable.subscribe(subject);

/* Prints SAME values for both consumers */
// consumer A: 0.8495447073368834
// consumer B: 0.8495447073368834

No comments:

Followers

Link