我有一个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'
答案 0 :(得分:2)
.flatMapLatest
和.flatMap
将Observable
类型作为其闭包的返回值。您需要返回包裹在可观察物内的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)