RxJava Operators: Zipping

November 11, 2018

Zipping()

Zipping allows us to take emissions from Observable which emit even different type of items and combine them into a single emission.

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> mySource1 = Observable.just("a", "b", "c", "d", "e");

        Observable<Integer> mySource2 = Observable.range(1, 10);

        Observable.zip(mySource1, mySource2, (s1, s2) -> s1 + "-" + s2)
                  .subscribe(System.out::println);
    }
}

The example will print out the paired items as single emissions. After the 5th item, the emission will stop.
One thing worth keeping in mind is that if a source is producing emissions faster than the other, the items will be queued up. This might cause increased memory usage.
A possible use-case for zipping could be to time emissions by using an Observable.interval() to zip with:

import io.reactivex.Observable;

import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        Observable<String> mySource = Observable.just("a", "b", "c", "d", "e");

        Observable<Long> timer = Observable.interval(1, TimeUnit.SECONDS);

        mySource.zipWith(timer, (s1, s2) -> s1)
                .subscribe(System.out::println);

        Thread.sleep(6000);
    }
}

As you can see in the example above, it is possible to use an operator called zipWith() to zip two Observables.

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami