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.
CancellationTokenSource
.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()
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"),
]
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
CancellationToken is just a single file, so instead of using SPM or CocoaPods, you could also just copy it into your project:
denit
of cancellation sourceCancellationToken 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.
link |
Stars: 17 |
Last commit: 6 weeks ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco