[英]How to return different types from flatMapLatest in RxSwift?
我正在使用驅動程序跟蹤RxSwift示例GitHub SignUp ,最后得到類似的東西。
我有一個執行身份驗證的網絡請求並返回一個Observable<AuthenticationResult>
,這樣我就有了這個:
public enum AuthenticationResult {
case canceled
case usernameEmpty
case passwordEmpty
case invalidCredentials
case granted(AccessToken)
case other(Error)
}
// Authentication result status
let authenticationResult: Driver<AuthenticationResult>
authenticationResult = input.loginTaps.withLatestFrom(usernameAndPassword)
.flatMapLatest({ (username, password) -> SharedSequence<DriverSharingStrategy, AuthenticationResult> in
return API.authenticate(username: username, password: password, applicationScope: .property).trackActivity(signingIn).asDriver(onErrorJustReturn: .canceled)
})
.flatMapLatest({ (result) -> SharedSequence<DriverSharingStrategy, AuthenticationResult> in
switch result {
case .granted(_):
// The closure is expecting a return value here that I don't have!
let portfoliosNavigationController = UINavigationController(rootViewController: PortfoliosTableViewController())
wireframe.show(viewController: portfoliosNavigationController)
default:
return wireframe.promptFor(result.description, cancelAction: "OK", actions: [])
.map({ (_) -> AuthenticationResult in
result
}).asDriver(onErrorJustReturn: result)
}
})
現在, 問題在於:
我的flatMapLatest
需要一個SharedSequence<DriverSharingStrategy, AuthenticationResult>
,我並不總是要返回!
在閉包內部, 如果驗證成功 ,我可以返回SharedSequence<DriverSharingStrategy, AuthenticationResult>
,因為我的wireframe.promptFor
返回一個observable。
但是,當身份驗證失敗時 ,我沒有可觀察的返回。 我的wireframe.show
方法沒有返回任何內容。
我該如何處理這種情況?
謝謝
假設切換案例.granted
是認證成功,您只需返回Observable.empty()
或Driver.empty()
。
通過在flatMap
操作中返回空驅動程序序列,意味着結束可觀察序列。 流將接收onCompleted
事件,您可以在流或操作成功時理解該事件。
然后,您可以在drive()
方法的onCompleted
閉包中找到以下代碼。
// Your observable stream / driver sequence
.drive(onCompleted: { [unowned wireframe] in
let portfoliosNavigationController = UINavigationController(rootViewController: PortfoliosTableViewController())
wireframe.show(viewController: portfoliosNavigationController)
}
這應該工作。
Driver
單元 通過使用驅動程序單元 ,您說您期望可觀察序列具有以下特征:
這在執行與UI相關的事情(例如您要執行的顯示導航控制器的操作)時非常有用。 如果是這種情況,請繼續使用驅動程序。
如果有一些機會你需要返回一個可觀察的序列,以便你可以輸出錯誤(因為你將執行一個可能出錯的可觀察操作,或者因為你想拋出一個錯誤來停止操作),那么你可以在Driver
實例上使用toObservable()
操作。
但要小心,因為你失去了在主線程上運行的斷言(顯示視圖控制器所需的斷言)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.