我正在使用RxSwift 2.0.0-beta
如何以拉链方式组合2个不同类型的可观察对象?
// This works
[just(1), just(1)].zip { intElements in
return intElements.count
}
// This doesn't
[just(1), just("one")].zip { differentTypeElements in
return differentTypeElements.count
}
Run Code Online (Sandbox Code Playgroud)
我目前的解决方法是将所有内容映射到组合类型的可选元组,然后将可选元组拉到非可选元组中.
let intObs = just(1)
.map { int -> (int: Int?, string: String?) in
return (int: int, string: nil)
}
let stringObs = just("string")
.map { string -> (int: Int?, string: String?) in
return (int: nil, string: string)
}
[intObs, stringObs].zip { (optionalPairs) -> (int: Int, string: String) in
return (int: optionalPairs[0].int!, string: optionalPairs[1].string!)
}
Run Code Online (Sandbox Code Playgroud)
但这显然很难看.有什么更好的方法?
Won*_*Kim 17
这适合我.我在Xcode7,RxSwift-2.0.0-beta中测试了它
zip(just(1), just("!")) { (a, b) in
return (a,b)
}
Run Code Online (Sandbox Code Playgroud)
这是如何使其适用于RxSwift 2.3+
Observable.zip(Observable.just(1), Observable.just("!")) {
return ($0, $1)
}
Run Code Online (Sandbox Code Playgroud)
要么
Observable.zip(Observable.just(1), Observable.just("!")) {
return (anyName0: $0, anyName1: $1)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11604 次 |
| 最近记录: |