Member-only story
RxJS: How to Use refCount
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 —…