DEV Community

Leonardo Maria Miliacca
Leonardo Maria Miliacca

Posted on

The RxJS concatenation strategies, pt 3/4

Welcome back! In this article I’ll illustrate another concatenation strategy used by the marvelous library RxJS.
First and foremost, if you didn’t checked out my previous articles, I suggest to do that now:

concatMap

mergeMap

In this article I’ll introduce you to the switchMap operator, which basically lets the developer to concatenate different events such that if an event in the events chain hasn’t completed, is erased when a new event is emitted.

Let’s look at the switchMap marble diagram:

switchMap marble table

To put that in a living example, let’s say that when a user type a letter (“A”, “B”, “C” in our case), the switchMap operators combines it with 1,2 and 3, and emits these value with an interval of 1 second.

Now, let’s suppose that the user types “A”, switchMap register the three new values “A1”, “A2”, and “A3” and emits “A1” immediately, then waits for a second before emitting “A2”. In the meantime, after (about) 0.8 seconds, the user types in “B”. The switchMap operator cancels all the scheduled events “A2” and “A3”, and replaces them with a new serie of “B1” (which is emitted immediately), “B2” and “B3”.

This operator is particularly useful when we have a form which perform a save at each value change. To avoid tenths of HTTP request calls, we’d probably want to use switchMap.

I hope the mechanism is a bit more clearer :)

Top comments (0)