Await for loop in book chapter4

for await _ in await NotificationCenter.default
.notifications(for: UIApplication.willResignActiveNotification) {

}

why here. before NotificationCenter.default there is an “await” also ?

for await _ in {AsyncSteam} should work.

I also had to double-check about this - it’s an interesting one.
The reason for the await before NotificationCenter.default .notifications(for: UIApplication.willResignActiveNotification) is not because it’s an async stream (as suggested in your comment).

The name of the notification is UIApplication.willResignActiveNotification and the whole UIApplication class is on @MainActor — thus when accessing the name property from an other task you need to use await.

If you wanted, you could optimize the code a little and store the value of UIApplication.willResign... into a local constant while you’re on the main actor and use the local variable directly to avoid the extra await in the loops.

2 Likes