Skip to content

What is the difference between concatMap and flatMap in RxJava

It seems that these 2 functions are pretty similar. They have same signature (accepting rx.functions.Func1<? super T, ? extends Observable<? extends R>> func), and their marble diagrams look exactly same. Can’t paste the pics here, but here’s one for concatMap, and here’s one for flatMap. There seems to be some subtle difference in the description of resulting Observable, where one produced by concatMap contains items that result from concatinating resulting Observables, and the one produced by flatMap contains items that result from first merging the resulting Observables, and emitting the result of that merger.

However, this subtlety is totally unclear to me. Can anyone give a better explanation of this difference, and ideally give some examples illustrating this difference.



As you wrote, the two functions are very similar and the subtle difference is how the output is created ( after the mapping function is applied).

Flat map uses merge operator while concatMap uses concat operator.

As you see the concatMap output sequence is ordered – all of the items emitted by the first Observable being emitted before any of the items emitted by the second Observable,
while flatMap output sequence is merged – the items emitted by the merged Observable may appear in any order, regardless of which source Observable they came from.

3 People found this is helpful