Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we call RxJS Subject as Multicast and Observable as Unicast?

I'm going through RxJS from sometime and i can't seem to understand why do we call RxJS Subject as Multicast and Observable as Unicast.

I understood that Subject is capable of emitting data using next()and like plain Observable, we can subscribe to them as well.

I found this from RxJS official website

A Subject is like an Observable, but can multicast to many Observers. 

Is this mean like a plain Observable cannot have multiple Observers?

like image 299
Rocky Avatar asked Jul 13 '19 15:07

Rocky


1 Answers

Consider this code:

const myObservable = new Observable<number>(subscriber => {
    const rdn = Math.floor(Math.random() * 200) + 1;
    subscriber.next(rdn);
});
myObservable
    .subscribe(a => console.log('Subscription A', a));
myObservable
    .subscribe(a => console.log('Subscription B', a));
    
// Result: 
// Subscription A 137
// Subscription B 8

Observable is unicast because each observer has its own instance of the data producer. On the other hand Observable is multicast if each observer receives notifications from the same producer, like this:

const rdn = Math.floor(Math.random() * 200) + 1;
const myObservable = new Observable<number>(subscriber => {
  subscriber.next(rdn);
});
myObservable
  .subscribe(a => console.log('Subscription A', a));
myObservable
  .subscribe(a => console.log('Subscription B', a));

// Result:
// Subscription A 149
// Subscription B 149

This last code snippet is not considering some treatments like errors and completions.

Subject is multicast because of this:

Internally to the Subject, subscribe does not invoke a new execution that delivers values. It simply registers the given Observer in a list of Observers, similarly to how addListener usually works in other libraries and languages.

Take some time to read this.

like image 168
Marcelo Vismari Avatar answered Oct 14 '22 11:10

Marcelo Vismari