What is the difference between flatmap and switchmap in RxJava?

Julian Go picture Julian Go · Jan 27, 2015 · Viewed 59.2k times · Source

The rxjava doc definition of switchmap is rather vague and it links to the same page as flatmap. What is the difference between the two operators?

Answer

dwursteisen picture dwursteisen · Jan 27, 2015

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