Skip to content

Instantly share code, notes, and snippets.

@mbrandonw
Last active June 26, 2022 20:42
Show Gist options
  • Save mbrandonw/0a85acfa9cecc993b603ff3549c2b83a to your computer and use it in GitHub Desktop.
Save mbrandonw/0a85acfa9cecc993b603ff3549c2b83a to your computer and use it in GitHub Desktop.

NotificationCenter.Notifications does not cooperatively cancel

FB10473067

When the following code is run in a playground or in an application:

let task = Task {
  for await _ in await NotificationCenter.default.notifications(named: UIApplication.userDidTakeScreenshotNotification) {
  }
  print(#line, "Sequence finished")
}

Task {
  task.cancel()
  await task.value
  print("Task finished")
}

Nothing is printed to the console.

I would expect that cancelling the task trickles down to cancelling the NotificationCenter.Notifications async sequence.

If we swap out notifications(named:) for another AsyncSequence, like a stream, it works as I expect by printing to the console:

let task = Task {
  for await _ in AsyncStream<Void> { _ in } {
  }
  print("Stream finished")
}

Task {
  task.cancel()
  await task.value
  print("Task finished")
}

Stream finished

Task finished

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment