[Pitch] Concurrency-Safe Notifications

Something about this change feels a little silly & redundant. At the very least, wouldn't it make sense to have a convenience method that just uses the message instance's isolation?

extension NotificationCenter {
  func post(_ message: Message) {
    self.post(message, isolation: message.isolation)
  }
}
1 Like

Would it be possible to include in the proposal why Message has Isolation as a primary associated type? It doesn't seem to be necessary in any of the public APIs, so curious how the authors found it could be useful in practice.

Going back to the proposal that added PATs to a bunch of standard library types, there were some rough guidelines that could be employed to understand when a PAT would be useful. Does any of that resonate with why Isolation is primary?

2 Likes

What will happen if a wrong type of observer passed into addObserver method? Compiler will not warn this:

struct BasicMessage: NotificationCenter.Message {
    static let name = Notification.Name("BasicMessage")
    let isolation = MyActor()
}

// Expected usage.
center.addObserver(BasicMessage.self) { message, isolation in ... }
// What will happen with this case?
center.addObserver(BasicMessage.self) { message in ... }

It seems can be fixed by adding a constraint to MainActor specialized addObserver:

public func addObserver<MessageType: Message>(
    _ notification: MessageType.Type,
    observer: @escaping @MainActor @Sendable (MessageType) -> Void
) -> ObservationToken 
where MessageType.Isolation == MainActor { ... }

// Compiler will warn "No exact matches in call to instance method 'addObserver'"
center.addObserver(BasicMessage.self) { message in ... }

But you can still call generic addObsever with a MainActor isolated message type:

struct MainActorMessage: NotificationCenter.Message {
    static let name = Notification.Name("MainActorMessage")
}

center.addObserver(MainActorMessage.self) { message, isolation in ... }

FYI

An updated version of this pitch is now under review here: [Review] SF-0011: Concurrency-Safe Notifications