RxJava Operators: combineLatest()

November 12, 2018

combineLatest()

The combineLatest() operator is quite similar to the zip() operator, but for every item which is emitted from one of the sources, it will be immediately coupled with the latest emissions from the other sources.
This operator will not queue up unpaired emissions for each source, but cache the items and pair only the latest one.

import io.reactivex.Observable;

import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        Observable<String> mySource1 = Observable.interval(250, TimeUnit.MILLISECONDS)
                                                 .map(x -> String.format("%s milliseconds", ((x+1)*250)));

        Observable<String> mySource2 = Observable.interval(1, TimeUnit.SECONDS)
                                                 .map(x -> String.format("%s seconds", (x+1)));

        Observable.combineLatest(mySource1, mySource2,
                                (s1, s2) -> String.format("Source1: %s, Source2: %s", s1, s2))
                  .subscribe(System.out::println);

        Thread.sleep(6000);
    }
}

One thing worth keeping in mind is that combineLatest() is sensitive to the order of the sources.

import io.reactivex.Observable;

public class Main {

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

        Observable<String> mySource2 = Observable.just("x");

        Observable<String> mySource3 = Observable.just("y");

        Observable.combineLatest(mySource1, mySource2, mySource3,
                                (s1, s2, s3) -> String.format("%s - %s - %s", s1, s2, s3))
                 .doOnComplete(() -> System.out.println("\n------\n"))
                 .subscribe(System.out::println);

        Observable.combineLatest(mySource3, mySource2, mySource1,
                (s1, s2, s3) -> String.format("%s - %s - %s", s3, s2, s1))
                .subscribe(System.out::println);
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami