mergeMap
, we run the risk of getting results back from the server in the wrong order. Let's illustrate this with an example.ABC
, and suppose the string ABC
is actually a special string where it will take the server a few extra seconds to reply.ABCX
. Since ABCX
is not considered a special string, the server replies very quickly and our app sets the suggestions for ABCX
.ABC
string, and our app receives that response and sets the search suggestions for ABC
, overwriting the suggestions for the ABCX
string, even though the request for that actually came afterwards.ABCX
why am I seeing the results for ABC
?" the user might think. To get around this problem we need to replace mergeMap
with switchMap
.switchMap
?switchMap
is very similar to mergeMap
, but with a very important distinction. Any events to be merged into the trunk stream are ignored if a new event comes in. Here is a marble diagram showing the behavior of switchMap
:mergeMap
will subscribe to (and invoke) a new observable without unsubscribing from any other observable created by a previous event. switchMap
on the other hand will automatically unsubscribe from any previous observable when a new event comes down the stream.mergeMap
, the red marble gets replaced with a red diamond and a subsequent red square. The interaction between the green and blue marble events are more interesting. Note that the green marble gets mapped to a green diamond immediately. And if enough time had passed, a green square would be pushed into the trunk stream but we do not see that here.switchMap
can be likened to a mergeMap
that "switches" to the more immediate incoming event and ignores all previously created event streams.switchMap
to the above example, the response for ABC
would be ignored and the suggestions for ABCX
would remain.switchMap
switchMap
instead of mergeMap
.switchMap
is more robust than the one we saw on the previous page with mergeMap
. The suggestions that the user sees will always eventually reflect the last thing the user typed. Thanks to this, we can guarantee a great user experience regardless of how the server responds.