- What if we want both values,
but we don't want to fire off our observable
for every single one?
Well, then, we can use switchMap.
Imagine you have a search bar.
Every time your user types in there,
you're going to query the results from a database.
Then imagine your user changes the search string
while you're still waiting for the query to return.
switchMap is a great operator in that instance
because it will cancel the old request
and replace it with a new one automatically.
So, in our example here,
switchMap will trigger the subscribe
once for each number,
but it will only give us the most recent letter
each time it fires
rather than all the letters,
like it did before.
Let's go ahead and take a look at that.
This time, we're going to keep all the code
exactly as it is now
and just replace mergeMap with switchMap.
So, again, we'll hold down the option key
so that we can type this just once,
change the mergeMap to switchMap
in both the import and in the code.
We're not going to change anything else.
And let's go back and look at the console log.
Now, just as expected,
it prints the console log once for each number
but we only get the most recent letter
rather than each letter.
Again, there are many operators,
so as you use RxJS in your own projects,
you can go back to the choose your own adventure page
and look for the operators
to do exactly what you need.