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
ABCis actually a special string where it will take the server a few extra seconds to reply.
ABCXis not considered a special string, the server replies very quickly and our app sets the suggestions for
ABCstring, and our app receives that response and sets the search suggestions for
ABC, overwriting the suggestions for the
ABCXstring, even though the request for that actually came afterwards.
ABCXwhy am I seeing the results for
ABC?" the user might think. To get around this problem we need to replace
switchMapis 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
mergeMapwill subscribe to (and invoke) a new observable without unsubscribing from any other observable created by a previous event.
switchMapon 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.
switchMapcan be likened to a
mergeMapthat "switches" to the more immediate incoming event and ignores all previously created event streams.
switchMapto the above example, the response for
ABCwould be ignored and the suggestions for
switchMapis 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.