使用flatMap快速切换viewModel

时间:2019-11-20 22:00:56

标签: swift rx-swift

我有一个viewModel,我在其中执行基于bool的检查。真假。这个值被传递到PublishSubject<Bool>()中,现在我想通过flatMapLatest获取最新值,并使用基于True / False值的另一个不同ViewModel进行导航

routeManager.errorOnNil().asObservable()

            .flatMapLatest { (code) -> Observable<RxSwift.Event<User>> in
            let params = code.values
                let challengeId = Int(params["challengeId"] as? String ?? "0")

            return self.provider.postVerifyApp(challengeId: login.challengeId!)
            .trackActivity(self.loading)
            .trackError(self.error)
            .materialize()
        }.subscribe(onNext: { [weak self] (event) in
            switch event {
            case .next(let token):
                log(token)
                if token.data != nil {
                    self?.dataStatus.onNext(true)
                } else {
                    self?.dataStatus.onNext(false)
                }
            case .error(let error):
                log(error.localizedDescription)
            default: break
            }
        }).disposed(by: rx.disposeBag)

切换位置

dataStatus.flatMapLatest { (status) -> ViewModel in
            if status {
                let viewModel = XXXViewModel(provider: self.provider)
                return viewModel
            } else {
                let viewModel = YYYYViewModel(provider: self.provider)
                return viewModel
            }
        }.subscribe()
            .disposed(by: rx.disposeBag)

这会导致错误Instance method 'flatMapLatest' requires that 'ViewModel' conform to 'ObservableConvertibleType'

1 个答案:

答案 0 :(得分:2)

.flatMapLatest.flatMapObservable类型作为其闭包的返回值。您需要返回包裹在可观察物内的viewModel.flatMapLatest会将其缩小,当您订阅时,将获得viewModel对象。

dataStatus.flatMapLatest { (status) -> Observable<ViewModel> in
            if status {
                let viewModel = XXXViewModel(provider: self.provider)
                return Observable.just(viewModel)
            } else {
                let viewModel = YYYYViewModel(provider: self.provider)
                return Observable.just(viewModel)
            }
        }.subscribe()
        .disposed(by: rx.disposeBag)