Nik*_*las 4 reactive-programming swift rx-swift
我正在使用RxSwift来完成我的代码.对于我目前的项目,我想将RxSwift的原则应用于来自LayerKit的一堆完成块:
layerClient.connectWithCompletion { (success, error) -> () in
if (!success) {
// Error
} else {
layerClient.requestAuthenticationNonceWithCompletion { (nonce, error) -> () in
// Even more blocks
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在考虑这样的事情:
// In extension
public func rx_connect() -> Observable<Bool> {
return create { observer in
self.connectWithCompletion { (success, error) -> ()in
if (success) {
observer.on(.Next(success))
observer.on(.Completed)
} else {
observer.on(.Error(error))
}
}
return NopDisposable.instance
}
}
public func rx_requestAuthenticationNonce() -> Observable<String> {
// Same for annother method
}
// In AppDelegate
self.layerClient.rx_connect()
.then() // requestAuthenticationNonceWithCompletion and use the nonce for next action
.then()
.subscribeNext(…
.onError(… // To catch all errors
Run Code Online (Sandbox Code Playgroud)
RxSwift没有then()方法.有没有其他方法来做这个链接的东西或我在如何使用ReactiveX一般错误?
是的,RxSwift没有then运营商,因为名称风险很大.
then可以在无扩展世界很多东西map一flatMap甚至switchLatest,根据上下文.
在这种情况下,我建议使用a,flatMap因为它将使用一个mapObservable of Observables 返回,在大多数情况下很难组合和管理.所以我会这样做:
self.layerClient.rx_connect()
.flatMap(){ _ in
return rx_requestAuthenticationNonce()
.catchError(displayError)
}
.subscribeNext(…
.onError(… // To catch all errors
Run Code Online (Sandbox Code Playgroud)
我会使用flatMap而不是map在这种情况下因为我能够捕获错误而不会终止序列以防万一rx_requestAuthenticationNonce()失败.
使用catchError运算符时要小心,此运算符将在恢复后终止序列,之后将忽略任何额外事件.
| 归档时间: |
|
| 查看次数: |
7569 次 |
| 最近记录: |