ObservableType.do‌ or .subscribe (Publisher.handleEvents or .sink)?

ObservableType.do‌ or .subscribe?

(The question, rephrased for Combine, involves swapping in Publisher.handleEvents and .sink, respectively.)

do (handleEvents) gives you a hook into a sequence’s events without triggering a subscription, while subscribe (sink) does the same and triggers a subscription—a way to remember this is the former returns an Observable (Publisher) and the latter returns a Disposable (AnyCancellable).

So, when should we use one over the other?

In the past, I’ve always placed effectful work in the do block, even if meant an empty subscribe() call at the end of a chain.

And I’m starting to change my mind here—putting that sole do work in the subscribe block makes the chain more succinct (there are definitely cases where it’s cleaner to use both to sort of group effects, e.g. UI-related versus persistence-related).

I dug up an old bit from Bryan Irace in an iOS Slack we’re a part of that puts it well:

do is for performing a side effect inside of a bigger chain

if all you’re doing is performing the side effect, just do that in your subscribe block