17 of 22 · Callbacks and concurrency
Pub/Sub
Publish/subscribe decouples senders from receivers: a publisher emits events to a channel, and any number of subscribers react without the publisher knowing who they are.
How it's wired
- Combine subjects/publishers or NotificationCenter.
- Here, one 'note saved' event updates three independent widgets.
| Part | Owns | Looks like |
|---|---|---|
| Publisher | Emit events | subject.send(_:), post(name:) |
| Channel | Fan out to subscribers | PassthroughSubject, NotificationCenter |
| Subscriber | React, own its subscription | sink + AnyCancellable, for await |
What gets hard
- You can't see who's listening by reading the code. Debugging becomes searching for notification names and subjects.
- Threading: NotificationCenter delivers on the posting thread; Combine on the upstream's scheduler. UI subscribers must hop to the main actor.
- Lifetime: block-based observers return a token you must keep; Combine subscriptions die with their AnyCancellable. Forget either and you leak or silently stop receiving.
- Ordering: subscribers run in an unspecified order and can trigger further events. Never depend on that order.
- Type safety: before iOS 26, notification names and userInfo dictionaries were untyped. iOS 26 adds typed messages (
NotificationCenter.MainActorMessage,AsyncMessage); otherwise prefer typed subjects or AsyncStream.
When I'd use pub/sub
| App-wide events | Sign-out, settings changed, note saved. |
|---|---|
| System events | Keyboard, app lifecycle (NotificationCenter). |
| A single consumer | A delegate, closure or async sequence instead. |
Compared
NotificationCenter vs Combine vs AsyncStream
| NotificationCenter | Combine | AsyncStream | |
|---|---|---|---|
| Type safety | userInfo dictionary | Typed | Typed |
| Cancellation | Remove observer | AnyCancellable | Task cancellation |
| Multiple subscribers | Yes | Yes | One per stream |
Expert notes
- Use it for broadcasts, and keep the event types typed and few.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain Pub/Sub in 30 seconds.
- Pub/sub lets a publisher emit events that any number of subscribers receive without knowing who they are: NotificationCenter, Combine subjects or AsyncStream.
- It's right for broadcasts like sign-out or a settings change.
- The cost is invisible coupling, since you can't see listeners in the code, plus threading and subscription lifetimes to manage.
- For one-to-one conversations I use a delegate or a closure.
Compare delegation, NotificationCenter and KVO by coupling and fan-out. When does each fit?
- Delegates and callbacks are one-to-one and loosely coupled, so use them when one owner needs to respond.
- NotificationCenter broadcasts to any number of observers and the poster doesn't know who's listening, so use it for app-wide events.
- KVO is one-to-many but tightly coupled to key paths on a specific object.
- Choose by who needs to know and how many.
A notification handler updates a label and sometimes misbehaves or crashes. What do you check?
- Check the thread first.
- Notifications arrive on the posting thread, so UI updates need to hop to the main queue.
- Then check lifetime.
- With the block API, keep the token from
addObserver(forName:object:queue:using:), remove it when you're done, and capture[weak self]in the block. - Passing
queue: .mainhandles the threading for you.
NotificationCenter is used everywhere and nobody knows who reacts to what. How do you make observation safer and clearer?
- Replace stringly-typed broadcasts with typed observer protocols, one method per event, with empty default implementations.
- Store observers as weak wrappers keyed by
ObjectIdentifier, so there are no retain cycles and insert and remove are constant time. - You regain type safety and can see who listens to what.
- The trade-off is more code and more protocols.
Your custom observer list keeps observers alive long after their screens close. How do you fix the storage?
- Store observers weakly.
- Wrap each in a struct holding
weak var observer: AnyObject?, key it byObjectIdentifierfor easy removal, and prune entries whose observer is nil whenever you notify. - Typed observer protocols with empty defaults let each observer pick events, and the compiler checks arguments.
- The cost is more internal code in an observation-heavy codebase.
A shared player takes observation closures, and old screens keep reacting after they're gone. What's the design flaw?
- Closures with no removal path outlive their screens.
- Tokens help.
- Store closures in a
[UUID: Handler]dictionary and return a token whosecancel()removes the entry. - But people forget to cancel.
- The sturdier fix is capturing the observer weakly and passing it into the closure, so observation ends when it deallocates.
- Match the technique to the observer's lifetime.