我面临的问题是链接2个请求并处理错误。
下面是我的代码示例:
func fbLogin() -> Observable<String> { ... }
func userLogin(request: Request) -> Observable<User> { ... }
let signedWithLogin = loginTaps
.asDriver(onErrorJustReturn: ())
.flatMapLatest { _ in
return fbLogin()
.map({ ReqestState<String>.loaded($0) })
.asDriver(onErrorRecover: { error in
return Driver.just(.error(error))
})
.startWith(.loading)
}
.map({ UserEndpoint.socialLogin(token: $0) })
.flatMapLatest { request in
return userLogin(request: request)
.map({ ReqestState<User>.loaded($0) })
.asDriver(onErrorRecover: { error in
return Driver.just(.error(error))
})
.startWith(.loading)
}
signedWithLogin
.drive(onNext: { response in
print(response)
})
.disposed(by: disposeBag)
问题是当我取消facebook登录弹出窗口时,我发送了
observer.onError(FBLoginManagerError.canceled)
错误。此错误首先捕获。asDriver(onErrorRecover: { error
方法,但不传递给.drive(onNext: { response
方法。如何捕捉
.asDriver(onErrorRecover: { error
方法中的所有错误? 最佳答案
穆克什是正确的,你可能应该避免Driver
直到结束。另外,当你只关心最后一种类型时,同时拥有这两种类型也没什么意义(RequestState
)
下面是一个简单的版本,我想它可以满足您的需要:
let signedWithLogin = loginTaps
.flatMapLatest {
fbLogin()
.map { UserEndpoint.socialLogin(token: $0) }
.flatMap { userLogin(request: $0) }
.map { RequestState.loaded($0) }
.catchError { .just(.error($0)) }
.startWith(.loading)
}
.asDriver(onErrorRecover: { fatalError($0.localizedDescription) }) // I'm using `fatalError()` here because if the above emits an error something has gone horribly wrong (like the RxSwift library isn't working anymore.)
signedWithLogin
.drive(onNext: { response in
print(response)
})
.disposed(by: disposeBag)
上面假设您将
RequestState<User>
函数更改为接受字符串而不是UserEndpoint.socialLogin(token:)
。它还假设
RequestState<String>
和fbLogin()
每个只发出一个值。您可能需要考虑将它们切换到userLogin(request:)
s。