I know the differences between concatMap
, flatMap
and switchMap
, but what if my stream only emits a single item and completes? In this case, functionally (pun not intended) these two operators are the same, but what about the performance? Which operator requires more resources, if the input only emits a single item? Most of the time the output is also a single item, if that is relevant.

- 4,007
- 5
- 32
- 44
1 Answers
In latest RxJava 1.x, if the source to concatMap
and flatMap
is identified as a scalar (i.e., just
), the operators are not instantiated but replaced by a custom internal Observable
via ScalarSynchronousSource.scalarFlatMap
which has lower overhead than the full operator. switchMap
could do the same but is not yet optimized for this case (it may not be worth it).
Otherwise, we can't detect if a regular Observable is going to emit a single item only thus the operators get all their inner workings executed. You can use Single
to work with sources emitting exaclty one item or an error.
We have a bunch of JMH benchmarks but I can't remember if there is one for comparing 1 element sources and these operators. Maybe I'll add one and post the results.
Edit
Here is a comparison benchmark.

- 69,132
- 14
- 157
- 192
-
So either `switchMap` or `concatMap` will be best for my case? – DariusL Jun 02 '16 at 07:21
-
concatMap is much better because flatMap adds overhead to draining a single source. – akarnokd Jun 02 '16 at 14:13