StepFlow 的目的是提供一种简单的方式来布局一组宏步骤以执行,然后运行它们。有很多好的开源库可以用来创建队列,或者执行一些小任务(无论是顺序还是并发),等等。因此,这绝对不是要取代它们的。也许在某个步骤中,您想使用库 X 来从某些 URL 下载所有图片,而在另一个步骤中,您想使用库 Y 来排队图像处理。
StepFlow 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod 'StepFlow'
只需创建步骤,并使用流程运行它们
let stepOne = Step { stepFlow, previousResult in
// previousResult in the first step is nil
// code to be executed on Step 1
stepFlow.finish(result: stepOneResult)
}
let stepTwo = Step { stepFlow, previousResult in
// previousResult in the second step is the result of step 1
// The error can be anything as long as it conforms to the ErrorType protocol
// code to be executed on Step 2
stepFlow.finish(error: someError)
}
Flow(steps: stepOne,stepTwo).start()
在步骤闭包中,不要忘记用某种结果或某种错误来结束该步骤。否则,流程将在这里停止。
StepFlow 提供了闭包,您可以在流程完成、结束错误或取消时运行它们。所有处理闭包都在主线程上运行。
Flow(steps: stepOne,stepTwo).onFinish{ finishState in
// code to be run after all steps finish
}.start()
如果您以错误完成步骤,流程将结束。
Flow(steps: stepOne,stepTwo).onError{ error in
// code to be executed if a step failed. The error will be sent here
}.onFinish{ finishState in
// If one step is finished with error. This block will not be executed.
// Unless, no onError closure is provided, in which case the Flow will
// default to this closure with finishState = .Failed(let error)
}.start()
如果流程被取消。
let f = Flow(steps: stepOne,stepTwo).onCancel{
// code to be executed if the flow is canceled.
}.onFinish{ finishState in
// If the flow is canceled. This block will not be executed.
// Unless, no onCancel closure is provided, in which case the Flow will
// default to this closure with finishState = .Canceled
}
f.start()
f.cancel()
StepFlow 的目的不是提供一种异步运行代码的方式。正如上面所述,有许多其他良好的选项,都得到了很好的文档说明,您可以在 StepFlow 旁边使用。尽管如此,您可以在创建步骤时将其设置为在后台线程上运行步骤。
let stepAsync = Step(onBackgroundThread : true) { stepFlow, previousResult in
// previousResult in the first step is nil
// code to be executed on a background thread
stepFlow.finish(result: stepOneResult)
}
默认情况下,所有步骤都在调用线程上执行。
Step Flow 在 MIT 许可证下提供。有关更多信息,请参阅 LICENSE 文件。