15 of 20 · 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 |
Swift example: untyped NotificationCenter vs. typed AsyncStream
Untyped userInfo dictionaries crash or silently fail on renames, and NotificationCenter delivers on the posting thread.
Before vs. after: typed broadcast with automatic Task cancellation
For app-wide events, a typed AsyncStream or NotificationCenter.notifications(named:) ties subscription lifetime to a Task.
// ❌ Before: untyped dictionary, wrong thread, forgotten token leaks observer.
NotificationCenter.default.addObserver(forName: .init("noteSaved"), object: nil, queue: nil) { note in
let saved = note.userInfo?["note"] as? ThankYouNote // untyped, runs on posting thread!
self.updateBanner(saved) // potential background UI crash
}
// ✅ After: typed payload + MainActor delivery + lifetime tied to Task.
func observeSavedNotes(
stream: AsyncStream<ThankYouNote>,
onUpdate: @escaping @MainActor (ThankYouNote) -> Void
) -> Task<Void, Never> {
Task { @MainActor in
for await note in stream {
onUpdate(note) // typed, main-actor safe, stops when Task cancels
}
}
}On iOS 26+, NotificationCenter.MainActorMessage also provides compile-time typed, main-actor notifications.
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 one publisher reach any number of subscribers without knowing them.
- On iOS that's
NotificationCenter, Combine subjects, or state observed through@Observable. - I use it for broadcasts, like sign-out or a settings change, and never for something that needs an answer.
- The cost is invisible coupling, because you can't find the listeners by reading the sender.
- Delivery happens on whatever thread posted, and every subscription has a lifetime someone must own.
- For one owner, I'd use a delegate or a closure.
Compare delegation, NotificationCenter and KVO by coupling and fan-out. When does each fit?
- I'd sort them by who needs to know.
- A delegate is one listener behind a typed protocol, so the sender can ask questions and get answers.
NotificationCenterreaches any number of listeners the poster can't see, which suits app-wide events but hides who reacts.- KVO watches one property on one object, and it only works on
NSObjectsubclasses with@objc dynamic. - In Swift models I'd reach for
@Observableinstead. - The cost rises with fan-out, because every extra listener makes a change harder to trace.
A notification handler updates a label and sometimes misbehaves or crashes. What do you check?
- I'd check the thread first.
- Observers run synchronously on the posting thread, so a post from a background queue updates UIKit off the main thread, which the Main Thread Checker flags.
- Passing
queue: .mainmoves delivery to the main queue. - Next I'd check lifetime, because the center keeps the block alive until its token is removed.
- A block capturing
selfstrongly keeps the screen alive and still reacting. - I'd capture
[weak self]and remove the token indeinit. - In Swift 6 code I'd iterate
notifications(named:)in a task the screen owns instead.
NotificationCenter is used everywhere and nobody knows who reacts to what. How do you make observation safer and clearer?
- I'd start with an inventory of every notification name, who posts it and who observes it.
- Some turn out to be one-to-one calls in disguise, and those become a delegate, a closure or a direct call.
- The real broadcasts get typed channels, either observer protocols or, on iOS 26,
NotificationCentermessage types with a typed payload. - Old and new coexist while I migrate one name at a time.
- The cost is more declared types, and that's deliberate.
- A reader, or an AI agent, can find every listener by searching for one type.
Your custom observer list keeps observers alive long after their screens close. How do you fix the storage?
- The list holds observers strongly, so it keeps alive screens it should only notify.
- I'd store a box with
weak var observer: AnyObject?and prune empty boxes on every notify. - Keying by
ObjectIdentifiermakes removal cheap, but an identifier can be reused once its object deallocates, so stale entries must go before a new object registers. - I'd also make the list
@MainActoror an actor, since adds and notifies come from different places. - On Apple platforms
NSHashTable.weakObjects()gives you the weak storage.
A shared player takes observation closures, and old screens keep reacting after they're gone. What's the design flaw?
- The player stores closures with no removal path, so each one keeps its captures alive and keeps running after its screen is gone.
- A cancel token helps, but people forget to cancel, which is the bug you already have.
- I'd make the token cancel in its own
deinit, the way Combine'sAnyCancellabledoes. - Then storing it on the screen ties observation to the screen's lifetime automatically.
- I'd only take the observer weakly instead when callers can't hold a token, like fire-and-forget registrations from Objective-C.
Read it in the app's source
Done with Pub/Sub? Mark it complete. Nailing its cards builds this pumpkin, row by row.