iOS RxSwift - 如何使用 Amb Operator?

iOS RxSwift - how to use Amb Operator?

我正在寻找 RxSwift 的 Amb() 运算符示例。

我有两个 observables - started 和 stopped 并且我想创建代码,如果其中一个 emits 就会执行,同时忽略另一个 emission。

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 类型是通用的,启动和停止的可观察对象正在过滤掉不同类型的结果。本质上,started 和 stopped 有不同的类型,因此 amb 不能与它们一起工作。

您可以通过执行 let foo = [started, stopped] 然后测试 foo 的类型来测试它。您可能会收到错误消息:

Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional

//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)