Zipping emissions – zip operator

The zip operator is quite interesting. Think of a situation where you're working with multiple Observable/Flowables and want to perform some kind of operation on each subsequent emission of each producer. The zip operator enables you to perform exactly that. It accumulates emissions of multiple producers to create a new emission via the specified function. So, let's look at a pictorial representation to delve deeper:

As the picture depicts, the zip operator accumulates emissions from multiple producers into a single emission. It also takes a function to apply on the emissions as the scan or reduce operator, but applies them to emissions from different producers.

For the sake of simplicity, we used two Observable in the preceding picture and the following example, but the zip operator works with up to nine Observables/Flowables.

Consider the following code:

    fun main(args: Array<String>) { 
      val observable1 = Observable.range(1,10) 
      val observable2 = Observable.range(11,10) 
      Observable.zip(observable1,observable2,  
io.reactivex.functions.BiFunction
<Int, Int, Int> { emissionO1, emissionO2 -> emissionO1+emissionO2 }).subscribe { println("Received $it") } }

The zip operator is defined in companion object (static method in Java) of the Observable class, thus can be directly accessed by writing Observable.zip itself. No need to access it through another instance. So, let's take a look at the output before we proceed:

In order to understand and use the zip operator better, you need to keep the following points about it in mind:

  • The zip operator works on each emission of the supplied producers. For example, if you pass three producers x, y, and z to the zip operator, it will accumulate the nth emission of x with the nth emission of y and z.
  • The zip operator waits for each of its producers to emit, before applying the function to them. For example, if you use Observable.interval as one of the producers in the zip operator, the zip operator will wait for each emission and will emit the accumulated values at the specified intervals as well.
  • If any of the producers notify onComplete or onError without emitting the item it was waiting for, then it'll discard all emissions afterwards, including that particular one from other producers as well. For example, if producer x emits 10 items, producer y emits 11 items, and producer z emits 8 items, the zip operator will accumulate the first 8 emissions from all the producers and will discard all remaining emissions from producer x and y.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.195.111