I'm using RxSwift 2.0.0-beta
How can I combine 2 observables of different types in a zip like manner?
// 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
}
The current workaround I have is to map everything to an optional tuple that combines the types, then zips optional tuples into a non-optional one.
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!)
}
That's clearly pretty ugly though. What is the better way?
.combineLatest() Combine the latest values from each supplied Observable using a supplied function. Both Observables need to emit an element for combining to happen. Operator receives a closure predicate that is applied to each emitted element. The latest elements from each Observable are combined.
The Zip method returns an Observable that applies a function of your choosing to the combination of items emitted, in sequence, by two (or more) other Observables, with the results of this function becoming the items emitted by the returned Observable.
- parameter onNext: Action to invoke for each element in the observable sequence. - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. - parameter onError: Action to invoke upon errored termination of the observable sequence.
The heart of the RxSwift framework is based on observable which is also known as a sequence. Observable is the sequence of data or events which can be subscribed and can be extended by applying different Rx operators like map, filter, flatMap, etc. It can receive data asynchronously.
Here is how to make it work for RxSwift 2.3+
Observable.zip(Observable.just(1), Observable.just("!")) {
return ($0, $1)
}
or
Observable.zip(Observable.just(1), Observable.just("!")) {
return (anyName0: $0, anyName1: $1)
}
This works for me. I tested it in Xcode7, RxSwift-2.0.0-beta
zip(just(1), just("!")) { (a, b) in
return (a,b)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With