【问题标题】:iOS RxSwift - how to use Amb Operator?iOS RxSwift - 如何使用 Amb 运算符?
【发布时间】:2018-09-02 11:12:23
【问题描述】:

我正在寻找 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 运算符来选择两个 observable 中的一个来首先发出值?

【问题讨论】:

    标签: ios swift3 reactive-programming rx-swift


    【解决方案1】:

    问题不在于您发布的代码。我的猜测是您的 Result 类型是通用的,并且启动和停止的可观察对象正在过滤掉不同类型的结果。从本质上讲,started 和stopped 有不同的类型,因此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)
    

    【讨论】:

    • 你是对的,我被 .filter 和 .map 弄糊涂了——它们被分成了多行。我需要 .amb 两个布尔可观察对象,并试图在它们的结果被映射之前这样做
    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多