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

Next
About this episode

Leave a rating/review

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

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 14. Canceling Tasks

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.

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 {
downloadTask?.cancel()

Partial Image Preview

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

TaskLocal

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
  .$supportsPartialDownloads
  .withValue(file.name.hasSuffix(".jpeg")) {
    fileData = try await model.downloadWithProgress(file: file)
  }
Button(action: { 🟩model.stopDownloads = true
if stopDownloads, !Self.supportsPartialDownloads {
  throw CancellationError()
}