RxJava 2 – FlatMap Example

In this tutorial, we’re going to get through some examples of the FlatMap operator of both Observable and Flowable types in RxJava 2.

1. Library Dependency

To use RxJava 2 with Maven, we need to add the following dependency to the pom.xml file:

To use RxJava 2 with Gradle:

2. FlatMap Examples Of The Observable Type

The FlatMap operator transforms an Observable by applying a function that we specify to each item emitted by the source Observable, where that function returns an Observable that itself emits items. The FlatMap then merges the emissions of these resulting Observables, emitting these merged results as its own sequence.

Let’s get to the first example of the FlatMap operator:

In the example, we have a list of sentences and the fromIterable method converts the list into an ObservableSource that emits the items in the list. For each sentence emitted, the FlatMap operator will:

  • Transform it by applying the split function, which will return an Observable that itself emits each word of the sentence.
  • Merges the emissions of these resulting Observables.
  • Emit these merged results as its own(the FlatMap) sequence.

Running the example will give us the result:

If you want to see more examples about creating RxJava 2 Observable, please visit How To Create Observable in RxJava 2.

3. FlatMap Examples Of The Flowable Type

The Flowable, which  has been introduced since RxJava 2, implements the Reactive-Streams pattern. Its FlatMap operator works the same way with the one of Observable, for example:

Running the example print out the result:

4. Summary

The quick tutorial has illustrated us how use FlatMap operator for Observable and Flowable types in RxJava 2. The sample source code presented in the tutorial is available on my Github project.