What is the difference between flatmap and switchmap in RxJava?

According to the documentation ( http://reactivex.io/documentation/operators/flatmap.html )

the switchMap is like the flatMap, but it will only emit items from the new observable until a new event is emitted from the source observable.

The marble diagram shows it well.
Notice the difference in the diagrams:

In switchMap the second original emission (green marble) does not emit its second mapped emission (green square), since the third original emission (blue marble) has begun and already emitted its first mapped emission (blue diamond). In other words, only the first of two mapped green emissions happens; no green square is emitted because the blue diamond beat it.

In flatMap, all mapped results will be emitted, even if they’re “stale”. In other words, both first and second of the mapped green emissions happen — a green square would’ve been emitted (if they used consistent map function; since they did not, you see the second green diamond, even though it is emitted after the first blue diamond)

switchMap
in switchMap if the original observable emits something new, previous emissions no longer produce mapped observables; this is an effective way to avoid stale results

flatMap

in switchMap if the original observable emits something new, previous emissions no longer produce mapped observables; this is an effective way to avoi stale results

Leave a Comment