【问题标题】:RxSwift - multiple Observable value within one ObservableRxSwift - 一个 Observable 中的多个 Observable 值
【发布时间】:2017-06-20 06:21:12
【问题描述】:

我想做一个类似这个例子的函数。

示例

let num1 = Driver<Int>
let num2 = Driver<Int>
let result = Driver<String>

num1 = Observable.just(...).asDriver()
num2 = Observable.just(...).asDriver()
result = ??? // When both num1 and num2 are subscribed, this becomes a higher value among them as String.

// This type of code will be used
/* 
if $0 >= $1 {
    return "num1 = \($0)"
} else {
    return "num2 = \($1)"
}
*/

如何实现?

【问题讨论】:

    标签: ios swift rx-swift


    【解决方案1】:

    如果可以,请不要使用变量。你已经有几个 observables 所以使用它们,但是,combineLatest 是这里的解决方案:

    import RxSwift
    
    let num1 = Observable.just(3)
    let num2 = Observable.just(5)
    let result = Observable.combineLatest(num1, num2).map { $0 >= $1 ? "num1 = \($0)" : "num2 = \($1)" }
    
    _ = result.subscribe(onNext: { print($0) })
    

    当它被放置在正确配置的游乐场时,上面会打印“num2 = 5”。

    【讨论】:

    • 谢谢。我在找这个!
    【解决方案2】:

    你可以在这里使用 RxSwift Variable 而不是 Driver 并且要监听两个 Observable,你可以使用 Observable.combineLatest(..) 方法。 下面是一个如何实现它的示例:

    let num1: Variable<Int>!
    let num2: Variable<Int>!
    
    let bag = DisposeBag()
    
    num1 = Variable(1)
    num2 = Variable(2)
    
    let result = Observable.combineLatest(num1.asObservable(), num2.asObservable()) { (n1, n2) -> String in
    
        if n1 >= n2 {
            return "num1 = \(n1)"
        } else {
            return "num2 = \(n2)"
        }
    }
    
    result.subscribe(onNext: { (res) in
        print("Result \(res)")
    }).addDisposableTo(bag)
    
    num1.value = 5
    num1.value = 8
    num2.value = 10
    num2.value = 7
    

    它输出:

    Result num2 = 2
    Result num1 = 5
    Result num1 = 8
    Result num2 = 10
    Result num1 = 8
    

    【讨论】:

    • 谢谢!但就我而言,num1 和 num2 也应该能够订阅其他变量。我的问题通过其他答案解决了,但你的回答也帮助我理解了 RxSwift。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    相关资源
    最近更新 更多