Understanding Publish, Connect, RefCount and Share in RxSwift

In this article, I aim to explain Publish, Connect, RefCount and Share operators
using RxSwift.

These operators are used together in different combinations. It’s important to understand
the difference between:

publish().connect()

and publish().refcount()/share().

Active and passive observables

Before I go to the heart of the matter, I want to mention the definition of hot
and cold observables.
For me, hot and cold observables are confusing and somewhat mystic terms
(to make things even more complicated… have you ever heard about warm and cool observables?).

Let’s rename “hot” observable to “active sequence” and “cold”
to “passive sequence”. These can be defined as follow:

Active sequences start producing notifications all the time regardless of subscriptions

An example of a passive sequence might be a network
request which is triggered by subscribing to it. On the other hand, active
sequences are web socket connections, timer events or text values coming from a UITextField.

Even if all subscriptions are disposed, observable still lives and produces events
under the hood. It behaves like active sequence. Now let’s compare that to
.publish().refcount().

The difference between .publish().connect() and .publish().refcount()

You can think of refcount() as magical system which handles disposal
of subscriptions for you. refcount() calls connect() automatically when first observer subscribes so there is no need for doing it manually.

Notice one thing: When we subscribe again, observable produces brand new elements.

Conclusion

Can you see the difference now? publish().connect() and publish().refcount() (or share() as a shortcut)
manage a disposal of observables differently.

When you’re using the publish().connect(), you have to dispose your observable manually.
Otherwise, it acts like active sequence and produces notifications all the time.

On the other hand, publish().refcount()/share() keeps track of how many other observers subscribe to observable
and does not disconnect from the observable until the last observer has done so.
In other words, when the subscriptions counter drops down to zero, observable is “killed” and does not produce any elements.