Skip to content

timvansteenis/swift-cancellationtoken

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

swift-cancellationtoken


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 the binding to Alamofire:

// 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

CocoaPods

CancellationToken is available for both iOS and OS X. 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 CocoaPods, you could also just copy it into your project:

Releases

  • 1.0.0 - 2017-02-23 - Cancel on denit of cancellation source
  • 0.3.0 - 2016-09-20 - Swift 3 support
  • 0.2.0 - 2015-09-11 - Swift 2 support
  • 0.1.1 - 2015-06-24 - No more circular references, fixes memory leak
  • 0.1.0 - 2015-03-31 - Initial public release
  • 0.0.0 - 2014-10-31 - Initial private version for project at Q42

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.

About

CancellationToken in Swift, modelled after the .NET version

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 88.1%
  • Ruby 11.9%