How do I use async/await with NotificationCenter?

In the Meet AsyncSequence talk, there's a very cool use case that's shown in one of the slides - the new notifications property on NotificationCenter is an async sequence and the code sample does something like:

let notification = await center.notifications(named: ....).first { ... }

This seems really intriguing and useful to me but I had a few questions about the details of how this works:

  1. What is the type of notification in this snippet? A Task? Where would I store this value?
  2. What context should this be invoked in, especially if I want to have a long-running notification filter running that will remain active for the lifetime of the app?

Basically, I'm curious to see an example of the code surrounding this snippet.

Replies

I honestly have not been able to get this to work either. It would be nice to see a demo of it in action.

  • Better start your own thread including the code which explains what you have tried till now.

  • I figured it out, solution below

Add a Comment

I figured out what was wrong with it:

this was what I was doing:

for await _ in NotificationCenter.default.notifications(named: UIDevice.orientationDidChangeNotification, object: self) {
    print("orientation changed") // This would never fire
}

I changed it to:

for await _ in NotificationCenter.default.notifications(named: UIDevice.orientationDidChangeNotification) {
    print("orientation changed") // This works
}

I guess I misunderstood what that object param was used for.

func observeNotifications() async {
    //Use any notification name appropriate
    let customNotificationName = Notification.Name("custom")

    let notifications = NotificationCenter.default.notifications(named: customNotificationName,
                                                                 object: nil) //If you want to receive only notifications from a specific sender then specify that in object 

    //notifications is an AsyncSequence
    //Each iteration in the loop would run asynchronously as when new notification is added to the sequence
    for await notification in notifications {
        print(notification)
    }
}