Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save robertmryan/135c2d816ebb00aeb5f18964c11d4fd8 to your computer and use it in GitHub Desktop.

Select an option

Save robertmryan/135c2d816ebb00aeb5f18964c11d4fd8 to your computer and use it in GitHub Desktop.
class ViewController: UIViewController {
private var task: Task<Void, Never>?
override func viewDidLoad() {
super.viewDidLoad()
let task = Task {
do {
try await self.test()
} catch is CancellationError { // this is another way to check for `CancellationError`
print("Task canceled..")
} catch {
if Task.isCancelled {
print("cancelled in catch block..") // we should never get here as the func should have thrown `CancelationError`, caught above
}
// whatever non-cancellation error handling you want here
print(error)
}
}
self.task = task
Task {
try await Task.sleep(for: .seconds(1))
task.cancel()
}
}
nonisolated func test() async throws { … }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment