refCount() and share()
The refCount() operator on ConnectableObservable is similar to autoConnect(1), which fires after getting one subscription. But there is one important difference; when it has no Observers anymore, it will dispose of itself and start over when a new one comes in. It does not persist the subscription to the source when it has no more Observers, and when another Observer follows, it will essentially "start over".
Look at this example: we have Observable.interval() emitting every second, and it is multicast with refCount(). Observer 1 takes five emissions, and Observer 2 takes two emissions. We stagger their subscriptions with our sleep() function to put three-second gaps between them. Because these two subscriptions are ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access