2017-06-20 105 views
0

我想做一個像這個例子一樣的函數。RxSwift - 在一個可觀測值內的多個可觀測值

例如

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)" 
} 
*/ 

如何實現的呢?

回答

1

不要使用變量,如果你能幫助它。你已經有幾個觀測,以便使用它們,但沒錯,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」時,它放置在一個正確配置的遊樂場。

+0

謝謝。我正在尋找這個! – Byoth

1

您可以在這裏使用RxSwift Variable而不是Driver並且在兩個Obserbles上監聽,您可以使用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 
+1

謝謝!但在我的情況下,'num1'和'num2'也應該能夠訂閱其他變量。我的問題是通過其他答案解決的,但您的回答也幫助我瞭解了RxSwift。 – Byoth

相關問題