DevPrep

All topics › Design patterns

Delegate, closure, Combine or AsyncSequence: how do you choose a callback channel?

Middle PRO

The gist

Delegates, closures, Combine and AsyncSequence solve the same problem — an object tells the outside world that something happened — but they differ along five axes: number of receivers (one or many), number of events (one or a stream), who owns the subscription, how to cancel it and which thread the call arrives on. The choice follows from these axes, not from fashion: delegates are not obsolete, and AsyncSequence does not replace everything.

For a single result ("the download finished") you usually need none of the four channels — async throws -> URL is enough. Channels are for repeating events such as progress.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store