Chop
使用 Chop 轻松编写同步、可测试的核心。
什么是 Chop?
Chop 是一个 Swift 微框架,提供对 任务 和 任务组 的实现。
- 任务 是异步过程的抽象,在其生命周期内可能会产生多个值(如渐进式图像或缓存后远程值)。它们还可以以错误结尾。任务是惰性的 - 这意味着在它们真正需要之前不会启动。此外,当任务不再被引用(即被回收)时,会取消任务,从而释放与它们关联的资源。
- 任务组 是任务的执行上下文。它们允许对任务施加唯一性约束,并在该上下文中应用各种行为。任务组在其被回收时释放它们管理的所有任务,这使得它们将特定任务绑定到用户界面的好方法。
以下是一个小的示例,说明如何使用 Chop 执行一个渐进式加载集合项的任务(例如,首先获取本地缓存值,然后获取远程值)。只允许执行一个任务;在第一个任务完成之前,忽略后续类似任务。
// The context in which the tasks can execute.
// `policy` describes what should be done if a task with an identical `taskId` is added to group.
// In this case we want to ignore subsequent tasks with the same `taskId` until the first is completed.
// Other options exist.
let taskGroup = TaskGroup(policy: .ignore)
self.isLoading = true
self.interactor
.fetchIssues(request, itemLimit: 10, progressive: true) // API that exposes a Chop'esque interface.
.onUpdate { [weak self] in
// Can be executed multiple times (i.e. providing first cached items, then remote items).
self?.items = $0
}
.onFailure { [weak self] in
// Executed only once if error occurs.
self?.handleError($0)
}
.onCompletion { [weak self] in
// Executed when the task has finished, regardless of result.
self?.isLoading = false
}
// `taskId` is optional - it will be
.registerIn(self.taskGroup, taskId: "itemFetch")
任务的创建方式如下
func fetchIssues(request: IssueRequest, itemLimit: UInt, progressive: Bool) -> Task<[Issue]> {
return Task {
let localItems = self.localDB.getItems(request)
// Send local items through to the Task subscribers.
$0(.update(localItems))
// The following operation is asynchronous.
var urlSessionTask = self.httpClient.getItems(request) { result in
switch result {
// Once again send data through to the Task subscribers.
case .success(let issues): $0(.update(issues))
// Or, otherwise, send error.
case .failure(let error): $0(.error(localResponse))
}
$0(.completion)
}
// In this closure we perform cleanup. It will be called if the task is finished or cancelled.
return { urlSessionTask.cancel(); urlSessionTask = nil }
}
}
只要任务被 TaskGroup
引用,任务就会执行工作。因此,如果销毁了 TaskGroup
,则会中断所有托管任务,您不必再关心它们。
需求
Chop
需要 Swift 3.2。同时支持 Swift 4。
安装
Chop
可以通过 CocoaPods 获取。要安装它,只需在您的 Podfile 中添加以下行
pod "Chop"
作者
伊万·莫斯科列夫,[email protected]
许可
Chop
在 MIT 许可下可用。更多信息请参阅 LICENSE 文件。