我正在寻找RxSwift的Amb()运算符的示例。
我有两个可观察的对象-启动和停止,我想创建一个代码,如果其中一个可以发出,则可以执行,而忽略了另一个可观察到的。
let started = viewModel.networkAPI.filter { result in
switch result {
case .success:
return true
case .failure:
return false
}
}
let stopped = viewModel.networkAPI.filter { result in
switch result {
case .success:
return true
case .failure:
return false
}
}
我尝试过:
Observable<Bool>.amb([started, stopped])
//error - Ambiguous reference to member 'amb'
//Found this candidate (RxSwift.ObservableType)
//Found this candidate (RxSwift.ObservableType)
和:
started.amb(stopped)
//error - Generic parameter 'O2' could not be inferred
我如何正确使用RxSwift AMB运算符从两个可观察对象中选择一个首先发出值?
答案 0 :(得分:3)
问题不在您发布的代码中。我的猜测是您的Result
类型是通用的,开始和停止的可观察值正在过滤掉不同类型的Result。本质上,开始和停止具有不同的类型,因此amb
不能与它们一起使用。
您可以通过执行let foo = [started, stopped]
然后测试foo
的类型来进行测试。您可能会收到错误:
异构集合文字只能推断为“ [Any]”;如果是故意的,则添加显式类型注释
//convert both to the same emission type,
//then apply .amb after one of them
let stoppedBoolType = stopped.map { _ -> Bool in
return false
}
started.map{ _ -> Bool in
return true
}.amb(stoppedBoolType)