![](/img/trans.png)
[英]Which RxSwift operator to use for uniquely emitted elements and how to?
[英]iOS RxSwift - how to use Amb Operator?
我正在尋找RxSwift的Amb()運算符的例子。
我有兩個observables - 啟動和停止,我想創建代碼,如果其中一個發出,將執行,而忽略來自另一個的發射。
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運算符選擇兩個可觀察量中的一個來首先發出值?
問題不在您發布的代碼中。 我的猜測是你的Result
類型是通用的,並且已啟動和已停止的observable正在過濾掉不同類型的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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.