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.
Observable
with theasObservable
method, you then get a multicast observable reflecting the Subject, but withoutnext
exposed for external use. So yes an observable can multicast. Both subjects and observables can have multiple observers, but multicast can emit multiple times to its observers, while unicast will emit once to its observers. – Sswshare()
,shareReplay()
and others. – Brodench