Home

Awesome

<img src="https://cloud.githubusercontent.com/assets/75655/5061903/76be2014-6dac-11e4-950b-2731f3c4cfef.png" alt="swift-cancellationtoken" width="360"> <hr>

A "cancellation token" is a little object that can be passed around to one or more asychronous tasks. This token can be used to indicate a user is no longer interested in the result of an asynchronous task.

By using a CancellationToken, the creation and cancellation of asynchronous tasks is separated into two distinct parts.

Usage

  1. Create a CancellationTokenSource.
  2. Get the token from the source.
  3. Pass the token to some asynchronous task.
  4. The asynchronous task may pass the token along to its subtasks.
  5. When no longer interested in the result of the asynchronous task; Cancel the source. This cancellation will propagate to the token, and all copies of the token.
  6. The asynchrounous task may choose to cancel its operation and fail in its own way.

Example

Here's an example based on network calls:

// Create a CancellationTokenSource and a CancellationToken
let source = CancellationTokenSource()
let token = source.token

// Start the asynchroneous downloading of a large file, passing in the cancellation token
request(largeFileUrl, cancellationToken: token)
  .response { response in
    if let error = response.error as? NSError {
      if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
        print("The downloading was cancelled")
      }
    }
    else {
      print("The response is available: \(response)")
    }
  }

// Some time later, request cancellation
source.cancel()

Installation

Swift Package Manager

SPM is a dependency manager for Swift projects.

Once you have SPM setup, add a dependency using Xcode or by editing Package.swift:

dependencies: [
    .package(url: "https://github.com/tomlokhorst/swift-cancellationtoken.git", from: "4.0.0"),
]

CocoaPods

CancellationToken is available for both iOS and macOS. Using CocoaPods, CancellationToken can be integrated into your Xcode project by specifying it in your Podfile:

pod 'CancellationToken'

Then, run the following command:

$ pod install

Manual

CancellationToken is just a single file, so instead of using SPM or CocoaPods, you could also just copy it into your project:

Releases

Licence & Credits

CancellationToken is written by Tom Lokhorst and available under the MIT license, so feel free to use it in commercial and non-commercial projects. This library modelled after the .NET cancellation model.