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?
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)
flatMap