// Make URLSessionDataTask conform to TCCancellable
extension URLSessionDataTask: TCCancellable {}
func download(from url: URL) async throws -> Data {
await withCheckedThrowingCancellableContinuation{ completion in
let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
if let data = data {
completion(.success(data))
} else if let error = error {
completion(.failure(error))
} else {
completion(.failure(Errors.unknownError))
}
}
task.resume()
return task
}
}
let channel = TCAsyncChannel<Int, Never>()
let filtered = channel
.filter { $0 % 2 == 0 }
Task {
// Available from iOS 13
for await number in filtered.asyncValues {
print("\(number)", terminator: " ")
}
}
try await channel.send(1)
try await channel.send(2)
try await channel.send(3)
try channel.send(completion: .finished)
TinkoffConcurrency 需要 Swift 5.5 及更高版本,并支持 Swift Concurrency。因此,所有 Xcode 13.0 及更高版本均可使用。建议使用 Xcode 13.2.1 或更高版本,因为它提供了与 iOS 13.0 及更高版本的向后兼容性。
TinkoffConcurrency 可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile
pod 'TinkoffConcurrency'
从 File (文件) 菜单中,选择 Add Packages... (添加包...)
输入 https://github.com/tinkoff-mobile-tech/TinkoffConcurrency
到仓库 URL
选择 Up to Next Major Version (更新到下一个主版本),并使用 1.2.0
作为最低版本
在 Add to Project (添加到项目) 中选择您的项目,然后点击 Add Package (添加包)
在打开的对话框中,选择要将库添加到的目标
文档在此处提供
要运行示例项目,请克隆仓库,并首先从 Example 目录运行 pod install
。示例应用程序是一个小型演示,展示了 withCheckedThrowingCancellableContinuation
对于可取消和不可取消任务的行为,并将它与原生的 withCheckedThrowingContinuation
行为进行比较。
示例应用程序需要 iOS 15.0 才能运行,因为它使用了新的 SwiftUI 功能。但这并不意味着在较旧的 iOS 版本上使用 TinkoffConcurrency 库有任何限制。
Timur Khamidov, t.khamidov@tinkoff.ru
Aleksandr Darovskikh, ext.adarovskikh@tinkoff.ru
TinkoffConcurrency 在 Apache 2.0 许可证下可用。有关更多信息,请参阅 LICENSE 文件。
感谢 Point-free 提供的测试 Combine scheduler