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.
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.
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With