iOS Concurrency with GCD & Operations

Sep 12 2023 · Swift 5.8, macOS 13, iOS 16, Xcode 14.3

Part 3: Operations & OperationQueues

22. Cancel Operations

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: 21. Challenge: Implement a Dependency Next episode: 23. Conclusion

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.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

You want to be able to cancel unnecessary operations to save your users’ data bandwidth, processing time and battery life. As soon as you add an operation to an operation queue, the only way to cancel it is to call its cancel method. But this only flips the values of its state properties. In particular, isCancelled becomes true. Your job is to code your operations so they check their isCancelled value, then do whatever is necessary: cancel tasks, notify servers, rollback database changes, throw exceptions, or generally clean up.

private var task: URLSessionDataTask?
task = URLSession.shared.dataTask(with: url) { [weak self] ...   // just add task = at the start of line
task = URLSession.shared.dataTask(with: url) { [weak self]
...
}
task?.resume()  // this is the new line 
override func cancel() {
  super.cancel()
  task?.cancel()
}
guard !self.isCancelled else { return }
guard !isCancelled else { return }
guard !isCancelled else { return }
private var operations: [[Operation]] = [[]]
operations = Array<[Operation]>(repeating: [], count: urls.count)
func cancelOperations(index: Int) {
  guard index < operations.count else { return }
  for operation in operations[index] {
    operation.cancel()
  }
}
cancelOperations(index: index)
guard index < operations.count else { return }
operations[index] = [tiltShiftOp, downloadOp]
.onDisappear {
  store.cancelOperations(index: image.id)
}