The refCount operator is used to automatically connect and disconnect an observable from its source when subscribers start and stop listening to it. The refCount operator returns a new Observable that automatically connects to the source Observable when the first subscriber subscribes to it, and automatically disconnects from the source Observable when the last subscriber unsubscribes from it.
Here is an example usage of the refCount operator:
index.tsx506 chars18 linesIn this example, we create an Observable source$ using the interval operator that emits a value every second, for a total of 5 times, and then completes. We then use the take operator to limit the number of emissions, the tap operator to log each emission, the publish operator to multicast the emissions to all subscribers, and finally the refCount operator to automatically connect and disconnect the Observable from its source.
We first subscribe to source$ using sub1. Since it is the first subscription, it starts the source subscription. We then simulate some delay before subscribing to source$ again using sub2. Since sub1 is still subscribed, sub2 shares the same source subscription. The console output should look something like this:
index.tsx208 chars25 lines
As you can see, both sub1 and sub2 receive the emissions from the source Observable, even though sub2 was subscribed after a delay. When both subscriptions are eventually unsubscribed, the source Observable is automatically disconnected.
gistlibby LogSnag