3
votes

I've been learning RxJs for a couple of weeks now and I can't seem to understand what exactly is the differences between Subjects and Multicasting an observable.

I found many sources that differentiate observables with subjects, but I couldn't find any source that differentiated Subjects with Multicasting-Observables

As per my understanding...

Multicasting: allow side-effects to be shared among multiple subscribers.

Subjects: is an Observable which shares a single execution path among observers.

My questions are:

  • What is the difference if both do the same thing?
  • When should you use a Subject?
  • When should you use multicasting?
1

1 Answers

4
votes

Basically "multicasting" means sharing one subscription to a source Observable among multiple observers. In RxJS this is always done via the multicast() operator that internally uses a Subject instance.

Subjects are objects that work as both Observable and observer at the same time. So typically you'll use Subjects to emit custom events whenever you want:

const s = new Subject();
s.next();
s.complete();

... but you can use it to subscribe to another Observable and then subscribe to this Subject multiple times which is the same thing as multicasting does:

const s = new Subject();
const source = ... // Observable
source.subscribe(s);

s.subscribe(...);
s.subscribe(...);
s.subscribe(...);

So there's only one subscription to source and 3 subscriptions (observers) to s thus you're multicasting emissions from source into 3 observers.