Member-only story

RxJS: How to Use refCount

Nicholas Jamieson
7 min readSep 3, 2017

--

Photo by Mike Wilson on Unsplash

My previous article — Understanding the publish and share Operators — looked only briefly at the refCount method. Let’s look at it more closely here.

What does refCount do?

To recap, the basic mental model for multicasting in RxJS involves: a source observable; a subject subscribed to the source; and multiple observers subscribed to the subject. The multicast operator encapsulates the subject-based infrastructure and returns a ConnectableObservable — upon which either the connect or refCount method can be called.

As its name suggests, refCount returns an observable that maintains a reference count of subscribers.

When an observer is subscribed to the reference-counted observable, the reference count is incremented and if the prior reference count was zero, the multicasting infrastructure’s subject is subscribed to the source observable. And when an observer is unsubscribed, the reference count is decremented and if the reference count drops to zero, the subject is unsubscribed from the source.

This reference counting behaviour can be used in two ways:

  • to automate the unsubscription of the subject from the source observable — when all observers have unsubscribed; or
  • to automate both the unsubscription of the subject from the source —…

--

--

Nicholas Jamieson
Nicholas Jamieson

Written by Nicholas Jamieson

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

Responses (10)