Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between publish and multicast operator in rxjs 5?

Tags:

rxjs5

I'm reading the rxjs manual, I'm a little confused about what's the difference between multicast and publish operators. They seem very similar.

like image 361
Aaron Shen Avatar asked Jun 25 '16 04:06

Aaron Shen


People also ask

What is multicast in RxJS?

multicast operator is a mechanism to introduce a Subject into the observable stream. Doing so allows sharing a single subscription to the underlying stream between multiple subscribers. Think of multicasting as casting values to multiple observers, hence the name of the operator.

What is multicast in angular?

Multicasting is the practice of broadcasting to a list of multiple subscribers in a single execution. With a multicasting observable, you don't register multiple listeners on the document, but instead re-use the first listener and send values out to each subscriber.

What is multicasting in Javascript?

Multicasting basically means that one Observable execution is shared among multiple subscribers. Subjects are like EventEmitters, they maintain a registry of many listeners. When calling subscribe on a Subject it does not invoke a new execution that delivers data.

What is publishReplay?

publishReplay makes it possible to share a single subscription to the underlying stream between multiple subscribers and replay a set of values that happened before the underlying stream completed.


2 Answers

I had the same question when reading http://reactivex.io/rxjs/manual/overview.html. So to make it clear, .publish() is just shorthand for .multicast(new Rx.Subject()) (and publishBehavior, publishLast, and publishReplay are similar but instantiate BehaviorSubject, AsyncSubject and ReplaySubject respectively).

like image 72
Ivan Avatar answered Sep 22 '22 08:09

Ivan


They are indeed very similar, and they have a history that makes it even more confusing.

In simple terms, publish is a special case of multicast. publish always creates a new subject (and then pretty much uses multicast), whereas multicast uses the subject provided as an argument.

like image 42
Ben Dadsetan Avatar answered Sep 23 '22 08:09

Ben Dadsetan