【问题标题】:How to return different types from flatMapLatest in RxSwift?如何从 RxSwift 中的 flatMapLatest 返回不同的类型?
【发布时间】:2017-06-26 08:50:04
【问题描述】:

我正在关注 RxSwift 示例 GitHub SignUp using Driver,最终得到了类似的结果。

我有一个执行身份验证并返回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&lt;DriverSharingStrategy, AuthenticationResult&gt;,但我并不总是返回!

在闭包内,我可以返回SharedSequence&lt;DriverSharingStrategy, AuthenticationResult&gt;如果身份验证成功,因为我的wireframe.promptFor 返回一个可观察的。

但是,当身份验证失败时,我没有可观察的返回。我的 wireframe.show 方法没有返回任何内容。

我该如何处理这种情况?

谢谢

【问题讨论】:

  • 身份验证失败时,API.authenticate 会返回什么?
  • 我得到一个 SharedSequence

标签: swift rx-swift


【解决方案1】:

假设 switch case .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)

}

应该可以的。

RxCocoa Driver 单元

通过使用Driver unit,您是说您期望一个可观察序列具有以下特征:

  • 不能出错
  • 在主调度器上观察
  • 分享副作用 (shareReplayLatestWhileConnected)

这在执行与 UI 相关的事情时通常很有用(例如您想要执行的操作是显示导航控制器)。如果是这种情况,请继续使用驱动程序。

但是如果我的流可能遇到错误怎么办?

如果出于某种原因您需要返回可观察序列以便出错(因为您要执行可能出错的可观察操作,或者因为您想抛出错误以停止操作),那么您可以在Driver 实例上使用toObservable() 操作。

但要小心,因为您失去了将在主线程上运行的断言(显示视图控制器需要它)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2013-05-14
    相关资源
    最近更新 更多