RxJava Operators: contains(), any(), all()

October 25, 2018

contains()

The contains() operator checks if a specific element is emitted by an Observable:

import io.reactivex.Observable;

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

        myObservable.contains("a")
                    .subscribe(System.out::println);
    }
}

any()

The any() operator will check if at least one emitted item meets the specified condition.
When this operator finds an element which satisfies the condition, it will emit true and call the onComplete().

import io.reactivex.Observable;

public class Main {
    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("a", "bb", "ccc", "dd", "e");

        myObservable.any(x -> x.length() == 3)
                    .subscribe(System.out::println);
    }
}

Calling the any() operator on Observable.empty() will result in false.

all()

The all() operator will check if all items emitted by an Observable satisfy a given condition.
When it encounters an emission which violates this condition, it will emit false and call the onComplete().

import io.reactivex.Observable;

public class Main {
    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("aaa", "bbb", "c", "dd", "eee");

        myObservable.all(x -> x.length() >= 3)
                    .subscribe(System.out::println);
    }
}

Calling the all() operator on Observable.empty() will result in true.

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami