Skip to content

Concurrency-Safe Notifications #822

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Nov 12, 2024

Conversation

cthielen
Copy link
Contributor

@cthielen cthielen commented Aug 5, 2024

This PR introduces a proposal for adopting Swift Concurrency in NotificationCenter.

@cthielen cthielen added the proposal This PR is for a proposal label Aug 5, 2024
@cthielen cthielen force-pushed the cthielen/notification-proposal branch from 6905774 to d45df0c Compare August 22, 2024 22:36
@cthielen cthielen force-pushed the cthielen/notification-proposal branch from fb8592c to 3205afd Compare November 8, 2024 22:08
static func makeNotification(_ message: Self) -> Notification
}

public protocol MainActorMessage: Message {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am wondering if this protocol should have a @MainActor annotation. Those types will only be sent and received from the MainActor anyways.

```swift
@available(FoundationPreview 0.5, *)
extension NotificationCenter {
public func addObserver<I: MessageIdentifier, M: AsyncMessage>(of subject: M.Subject,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How can those methods take an async closure while not being async themselves? Where is the task spawned that calls the observer closures?

If the addObserver method takes an async closure I would have expected that method to become async itself. Something more like this

await center.observe(of: subject, for: identifier) { message
  // do something async with the message
  await process(message)
}

This way you also don't need ObservationTokens but can just rely on task cancellation which IMO fits better into the Concurrency paradigms.

@itingliu
Copy link
Contributor

@swift-ci please test

@iCharlesHu iCharlesHu merged commit 221a0dd into swiftlang:main Nov 12, 2024
3 checks passed
@cthielen cthielen deleted the cthielen/notification-proposal branch June 26, 2025 02:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
proposal This PR is for a proposal
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants