RxSwift: use zip with different types of observables

I am using RxSwift 2.0.0-beta p>

How can I combine 2 observable different types as zip?

// 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 extra tuple that combines the types, and then replace the optional tuples with the 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!) } 

This is clearly pretty ugly. What is the best way?

+5
source share
2 answers

This works for me. I tested it in Xcode7, RxSwift-2.0.0-beta p>

 zip(just(1), just("!")) { (a, b) in return (a,b) } 
+11
source

Here's how to do it 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) } 
+4
source

Source: https://habr.com/ru/post/1237423/


All Articles