Sven Bendel
A droid's life

A droid's life

RxJava: flattening a stream of Iterables

Photo by Jon Flobrant on Unsplash

RxJava: flattening a stream of Iterables

Sven Bendel's photo
Sven Bendel
·Apr 28, 2017·

1 min read

Today I finally stumbled upon the solution of a really trivial RX problem: Suppose you have an Observable which returns Lists of items. Like Observable<List<String>>. You often receive something like this as responses from web APIs.

However chances are you want to operate on the single items, in this case the Strings.

flatMapIterable to the rescue! This handy operator flattens a stream of Iterables into a stream generated from the single items of these Iterables by means of a mapping function. Whoa — sounds complicated?

Let’s have a look at the marble diagram:

Source: RxJava’s Javadoc

If we now just use the identity function as mapping function we get exactly what we need.

listEmittingObservable.flatMapIterable { item -> item }

or using Kotlin’s it operator:

listEmittingObservable.flatMapIterable { it }

Now we can continue operating on the single items. Just what we want. Problem solved.

 
Share this