sainture
2/25/2018 - 5:51 AM

Subject vs Observable

Subject vs Observable

/* In order to understand the difference between a Subject and an Observable, you need to be aware of two distinct concepts
– A data producer
– A data consumer

An observable, by definition is a data producer. Albeit a special kind that can produce data over time.

A Subject on the other hand can act as both – a data producer and a data consumer.

This implies two things.
1. A subject can be subscribed to, just like an observable.
2. A subject can subscribe to other observables.

That being said, there is one critical difference between a subject and an 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

*/

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


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

// Observable wrapped in a subject, causing shared execution
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

// You can also manually broadcast data from a subject to it observers using 
// the next() function as shown below.