RxJava Operators: takeWhile(), skipWhile()

October 17, 2018

In a previous post we have seen the take() and skip() operators.
There is another variant of these operators: takeWhile() and skipWhile().
To be precise, actually two other variants exist, because takeUntil() and skipUntil() are also available.

takeWhile()

This operator will take emissions while a condition based on each emission is true. When it encounters the first item which violates this condition, takeWhile() calls the onComplete() method.
For example if we want to take emissions while their value is lower than 5:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<Integer> myObservable = Observable.range(0, 10);

        myObservable.takeWhile(x -> x < 5)
                    .subscribe(System.out::println);
    }
}

skipWhile()

The skipWhile() operator is similar to the takeWhile() operator: it skips emissions while they satisfy a condition. Starting with the first item which violates the condition, the emissions start to get through this operator.
For example if we want to skip emissions while their value is lower than 5:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<Integer> myObservable = Observable.range(0, 10);

        myObservable.skipWhile(x -> x < 5)
                    .subscribe(System.out::println);
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami