RxJS: Calling publish with a Selector

Nicholas Jamieson
4 min readApr 2, 2019
Photo by Beatriz Pérez Moya on Unsplash

The publish and publishReplay operators can be called in two ways: either with or without a selector function. Let’s look at the differences and at why you should almost always pass a selector.

Without a selector

When publish is called without a selector, it returns a particular type of observable: a ConnectableObservable.

A ConnectableObservable is a little unusual. It does not connect — i.e. subscribe — to its source when a subscriber subscribes. Instead, a ConnectableObservable subscribes to its source when its connect method is called.

This behaviour can be used to control the order in which subscriptions occur and to compose observables before a subscription is made to the source.

Let’s look at an example.

I’ve seen a ConnectableObservable used in a Stack Overflow answer on several occasions, so let’s make up a question and then answer it:

How can I compose an observable so that a specified, initial value is emitted if the source observable does not emit a value within a specified duration?

Here’s a solution that uses race:

--

--

Nicholas Jamieson

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