Handling Cancellation in Combine Swift with Example

Deepak Carpenter
Appgrid
Published in
2 min readJun 1, 2023

Asynchronous operations, such as image downloading, often require cancellation support to optimize resource utilization and improve user experience. In Combine, Apple’s framework for reactive programming, you can leverage the checkCancellation operator to handle cancellation effectively. In this blog post, we'll explore the checkCancellation operator in Combine and demonstrate its usage with an example of image downloading.

Understanding checkCancellation in Combine: The checkCancellation operator in Combine allows you to gracefully handle cancellations during asynchronous operations. It provides a mechanism to detect cancellation signals and perform cleanup actions, ensuring that resources are properly released when a subscription is canceled.

An example of Image Downloading with Cancellation Support

import Combine

enum ImageError: Error {
case invalidURL
case downloadFailed
}

class ImageDownloader {
private var cancellables = Set<AnyCancellable>()

func downloadImage(from url: URL) -> AnyPublisher<Data, ImageError> {
URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.checkCancellation()
.mapError { _ in ImageError.downloadFailed }
.eraseToAnyPublisher()
}

func cancelAllDownloads() {
cancellables.removeAll()
}
}

let downloader = ImageDownloader()

let url = URL(string: "https://example.com/image.jpg")!
let cancellable = downloader.downloadImage(from: url)
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
// Image download completed successfully
break
case .failure(let error):
// Handle download failure
print("Image download failed: \(error)")
}
}, receiveValue: { imageData in
// Process the downloaded image data
// ...
})

// Cancel the download
downloader.cancelAllDownloads()

In this example, we create an ImageDownloader class that handles image downloading using Combine. The downloadImage(from:) function uses the dataTaskPublisher(for:) method from URLSession to initiate the download task. We apply the checkCancellation operator to the pipeline to ensure cancellation is handled appropriately.

The cancelAllDownloads() method cancels all ongoing downloads by removing all stored cancellables. You can call this method to cancel any pending image downloads.

By utilizing the checkCancellation operator, you can handle cancellations gracefully and clean up any resources associated with the download task. This ensures that network requests are terminated properly and resources are released promptly.

The checkCancellation operator in Combine provides a powerful tool for handling cancellations during asynchronous operations. By incorporating cancellation support into your code, you can optimize resource utilization and enhance the user experience.

In this blog post, we explored the usage of checkCancellation in Combine with an example of image downloading. By applying this operator to your Combine pipelines, you can effectively handle cancellations and ensure proper resource cleanup.

Remember to consider cancellation support when designing reactive and asynchronous operations, such as image downloading. By leveraging the capabilities of Combine and the checkCancellation operator, you can build robust and responsive applications that gracefully handle cancellations during asynchronous tasks.

Cheers!
Happy Coding!

--

--