RxJava: Reducing Operators

- 3 mins

Sometimes, it’s useful to take a series of emissions and consolidate them into a single emission (usually Single).
Nearly all of reducing operators only work on a finite Observable (that calls onComplete()).

count()

This operator will count the number of emissions and emit through a Single once onComplete() is called:

fun main() {
    Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
        .count()
        .subscribe { s -> println("Received: $s") }
}
Received: 5

reduce()

The reduce() operator is syntactically identical to scan(), but it only emits the final accumulation when the source calls onComplete():

fun main() {
    Observable.just(1, 1, 2, 3, 5)
        .reduce { total, next -> total + next }
        .subscribe { println("Received: $it") }
}
Received: 12

It’s possible to pass a seed argument that will serve as the initial value to accumulate on. The seed value should be immutable (collect() or seedWith() should be used for mutables).

all()

This operator verifies that each emission qualifies with a specified condition and return a Single<Boolean>:

fun main() {
    Observable.just(1, 5, 12, 7,3)
        .all { it < 10 }
        .subscribe { b -> println("Received: $b") }
}
Received: false

Calling all() on an empty Observable, will emit true due to the principle of vacuous truth.

any()

This operator will check whether at least one emission meets a specific criterion and return a Single<Boolean>:

fun main() {
    Observable.just(1, 5, 12, 7, 3)
        .any { it > 10 }
        .subscribe { b -> println("Received: $b") }
}
Received: true

Calling any() on an empty Observable, will emit false due to the principle of vacuous truth.

contains()

This operator will check whether a specific element is ever emitted from an Observable (based on the hashCode()/equals() implementation) :

fun main() {
    Observable.just(1, 5, 12, 7, 3)
        .contains(12)
        .subscribe { b -> println("Received: $b") }
}
Received: true
Mouaad Aallam

Mouaad Aallam

Software Engineer

rss facebook twitter bsky github youtube mail spotify instagram linkedin google pinterest medium vimeo mastodon gitlab docker