Modern Concurrency: Getting Started

Oct 18 2022 Swift 5.5, iOS 15, Xcode 13.4

Part 2: Asynchronous Sequences

14. Canceling Tasks

Episode complete

Play next episode

Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 13. Downloading Chunks Next episode: 15. Using Combine

Xcode 14 beta detects a race condition for stopDownloads when you tap Cancel Now while using the Cloud 9 plan. Move stopDownloads and reset() to @MainActor and await the variable in the private downloadWithProgress method:

while await !stopDownloads, !accumulator.checkCompleted() {
if await stopDownloads, !Self.supportsPartialDownloads {
@MainActor var stopDownloads = false
@MainActor func reset() {

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a Professional subscription.

Make sure the course server is running and continue with your project from the previous episode or open the starter project for this episode.

Canceling Tasks

Why is it important to cancel tasks in a timely manner? Try this:

@State var downloadTask: Task<Void, Error>?
downloadTask = 🟥Task {

Partial Image Preview

What if you want to cancel a download task without leaving DownloadView? Look in SuperStorageModel.


Say hello to the TaskLocal property wrapper!

@TaskLocal static var supportsPartialDownloads = false
try await SuperStorageModel {
    fileData = try await model.downloadWithProgress(file: file)
try await SuperStorageModel
  .withValue(".jpeg")) {
    fileData = try await model.downloadWithProgress(file: file)
Button(action: { 🟩model.stopDownloads = true
if stopDownloads, !Self.supportsPartialDownloads {
  throw CancellationError()