SwiftPumpkin

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

send(event)DeliversDeliversPublisherEmits eventsChannelSubject / centerSubscriberReactsSubscriberReacts
calls or tellsreports backThe publisher never knows who is listening, or how many.
  • Combine subjects/publishers or NotificationCenter.
  • Here, one 'note saved' event updates three independent widgets.
PartOwnsLooks like
PublisherEmit eventssubject.send(_:), post(name:)
ChannelFan out to subscribersPassthroughSubject, NotificationCenter
SubscriberReact, own its subscriptionsink + 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 eventsSign-out, settings changed, note saved.
System eventsKeyboard, app lifecycle (NotificationCenter).
A single consumerA delegate, closure or async sequence instead.

Compared

NotificationCenter vs Combine vs AsyncStream

NotificationCenterCombineAsyncStream
Type safetyuserInfo dictionaryTypedTyped
CancellationRemove observerAnyCancellableTask cancellation
Multiple subscribersYesYesOne 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.

30-second answer

Explain Pub/Sub in 30 seconds.

SwiftAsked directly

Compare delegation, NotificationCenter and KVO by coupling and fan-out. When does each fit?

iOS codingAsked indirectly

A notification handler updates a label and sometimes misbehaves or crashes. What do you check?

System designAsked indirectly

NotificationCenter is used everywhere and nobody knows who reacts to what. How do you make observation safer and clearer?

iOS codingAsked indirectly

Your custom observer list keeps observers alive long after their screens close. How do you fix the storage?

iOS codingAsked indirectly

A shared player takes observation closures, and old screens keep reacting after they're gone. What's the design flaw?

Read it in the app's source

Done with Pub/Sub? Mark it complete. Nailing its cards builds this pumpkin, row by row.