RxJava Operators: count(), reduce()

October 24, 2018

count()

The operator count() is one of the operators which take a series of emissions and consolidate them into a single emission, usually emitted via a Single.
As the name suggests, this operator counts the number of emissions:

import io.reactivex.Observable;

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

        observable.count()
                  .subscribe(System.out::println);
    }
}

This operator, like most of the operators which consolidate emissions into a single result, cannot be used on infinite Observables. For such cases, you could consider using scan() to have a “rolling” counter.

reduce()

The reduce() operator is very similar to the scan() operator, but it emits only the final result:

import io.reactivex.Observable;

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

        myObservable.reduce((x, y) -> x + y)
                    .subscribe(System.out::println);
    }
}

Just as with scan(), it is possible to provide a starting seed value:

import io.reactivex.Observable;

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

        myObservable.reduce("Result: ", (x, y) -> x + y)
                    .subscribe(System.out::println);
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami