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

⇐ Notes archive

(This is an entry in my technical notebook. There will likely be typos, mistakes, or wider logical leaps — the intent here is to “let others look over my shoulder while I figure things out.”)

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