RxJava Operators: Ambiguous

November 9, 2018


The amb() operator takes an Iterable<Observable> as parameter and will emit the emissions of the first Observable which emits anything and disposes the other Observables.
A possible use-case for this operator could be that you have multiple sources for the same items and you don’t care which source provides the answer, you just want the first, fastest answer.

import io.reactivex.Observable;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        Observable<String> mySource1 = Observable.interval(1, TimeUnit.SECONDS)
                                                 .map(s -> (s + 1) + " second(s) passed!");

        Observable<String> mySource2 = Observable.interval(400, TimeUnit.MILLISECONDS)
                                                 .map(s -> ((s + 1) * 300) + " millisecond(s) passed!");

        Observable.amb(Arrays.asList(mySource1, mySource2))
                  .subscribe(x -> System.out.println("Received: " + x));



András Döbröntey

About the Author

András Döbröntey

Leave a Comment: