RxScala "zip" multiple Observables

198 views Asked by At

In RxScala how to "zip" more than 2 Observables?

val ob1: Observable[Int] = Observable.from(Future(10))
val ob2: Observable[Int] = Observable.from(Future(20))
val ob3: Observable[Int] = Observable.from(Future(30))

"zip" works perfect with 2 Observables

val obComb: Observable[(Int, Int, Int)] = ob1 zip ob2

How do we "zip" more than 2 Observables?

3

There are 3 answers

0
sarveshseri On BEST ANSWER

You can use zipWith which lets you provide your "zipping" function.

val obComb = ob1
  .zipWith(ob2)({ case (x1, x2) => (x1, x2) })
  .zipWith(ob3)({ case ((x1, x2), x3) => (x1, x2, x3) })
0
Samuel Gruetter On

Since zipping more than two Observables can't be defined "nicely" as an instance method, it's defined as a "static" method in the companion object. That is, to zip three Observables, you write

val obComb = Observable.zip(ob1, ob2, ob3)
0
proximator On

If you have more than 3 observables, you can also use:

val allObs = Observable.from(List(ob1, ob2, ob3))
val zipObs = Observable.zip(allObs)

If you don't like the static way, you can also try:

val zipObs = ob1 zip ob2 zip ob3 map {
   case ((a, b), c) => (a, b, c)
}