RxJS: multicast’s Secret

Nicholas Jamieson
4 min readAug 19, 2017
Photo by Tim Mossholder on Unsplash

multicast has a secret. And so does publish — which wraps multicast. And it’s sometimes really useful.

The secret

The documentation for multicast and publish mentions a ConnectableObservable. A connectable observable is type of observable that waits until its connect method is called before it begins emitting notifications to subscribers. However, the multicast and publish operators don’t always return a connectable observable.

Let’s start by looking at the source code for publish:

It’s clear that publish is just a thin wrapper around multicast. It creates a subject, which is passed to multicast along with the optional selector function. The interesting bit is inside the multicast implementation, which contains the following code:

multicast will only return a connectable observable if a selector function is not specified. If a function is specified, the lift mechanism will be used to allow the source observable to create an observable of the appropriate type. There will be no need to call connect on the returned observable and the source observable will be shared within the scope of the selector function.

That means that multicast (and publish) can be used to easily implement the local sharing of a source observable.

Local sharing with publish

Let’s look at an example that uses publish.

RxJS includes a defaultIfEmpty operator which takes a value that’s to be emitted if the source observable is empty. Sometimes, it’s useful be be able to specify a default observable — rather than a single value — so let’s implement a defaultObservableIfEmpty function that can be used with the let operator.

--

--

Nicholas Jamieson

RxJS core team member; front-end developer; mentor; speaker; open-source contributor