我有一个第三方SDK,其架构如下:
TheirService
)TheirServiceDelegate
,如果调用成功,则将收到通知onSuccess
;如果调用失败,则将收到onFailure
。问题在于TheirService
的方法彼此依赖,所以我最终遇到了“链式反应”,TheirService
的每个下一个方法都是从上一个回调中调用的。
请注意,TheirService
是单线程的,对于在开始下一个方法之前必须先完成之前的方法确实很挑剔。
当前我与服务的交互如下:
protocol MyClientListener {
notifyOnFailure()
notifyOnResult(result: SomeObject)
}
class MyClient: TheirServiceDelegate {
static let instance = MyClient()
let myService = TheirService()
var myResult: SomeObject?
var resultListener: MyClientListener
private init() { }
func start(resultListener: MyClientListener) {
self.resultListener = resultListener
myService.initialize()
}
// TheirServiceDelegate method
func onInitializeSuccess() {
myService.bootstrap()
}
// TheirServiceDelegate method
func onBootstrapSuccess() {
myService.login(user, password)
}
// TheirServiceDelegate method
func onLoginSuccess() {
myService.doSomethingUsefulStep1()
}
// TheirServiceDelegate method
func onDoSomethingUsefulStep1Success() {
myService.doSomethingUsefulStep2()
}
// TheirServiceDelegate method
func onDoSomethingUsefulStep2Success(result: SomeObject) {
// ah, look, now I have some object I actually wanted!
resultListener.notifyOnResult(result)
}
}
我还必须处理每个失败案例。而且我不能跳过或更改步骤的顺序,这会造成某种尴尬的状态机。
相反,我想通过逻辑功能与服务进行交互,这些逻辑功能从头到尾完成流程的某些阶段,并等待步骤之间的结果:
class MyClient {
static let instance = MyClient()
let myService = MyService()
private init() { }
func connect() throws {
myService.initialize()
// wait for success or failure, throw on failure
myService.bootstrap()
// wait for success or failure, throw on failure
myService.login(user, password)
// wait for success or failure, throw on failure
}
func doSomethingUseful() -> SomeObject {
myService.doSomethingUsefulStep1()
// wait for success or failure, throw on failure
myService.doSomethingUsefulStep2()
// wait for success or failure, throw on failure
// on success, it will get an object it could return
}
这样称呼:
try MyClient.instance.connect()
let x = try MyClient.instance.doSomethingUseful()
那么,有什么方法可以将“等待成功或失败”注释变成等待该单线程服务回叫的实际代码?在那种情况下适合代表?