SwiftPumpkin

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

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

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