How does task cancellation work?
The essence
Cancellation in Swift Concurrency is cooperative: task.cancel() only sets a flag and marks every child task in the tree. Nothing gets interrupted — the code must check the flag and wind down on its own. A task that never looks at Task.isCancelled runs to completion as if no cancellation happened.
Ways to react:
Task.isCancelled— check and decide for yourself what to do.try Task.checkCancellation()— throwCancellationErrorif cancelled.withTaskCancellationHandler(operation:onCancel:)— run code immediately at the moment of cancellation (close a connection, stop a driver), even if the task is currently suspended.- Most system async APIs (
URLSession,Task.sleep,AsyncSequence) check cancellation themselves and throwCancellationErrororURLError.cancelled.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep