Preventing Race Conditions with switchMap

Let's see the switchMap operator of RxJS that can be used to prevent race conditions.

In the Days of Olde, when magic still roamed the land, a High Programmer insulted a Network, and ever since then, the networks have had it out for us programmers.

Race conditions can seriously affect the working of our application if we don’t handle them.

A typeahead race condition bug typically manifests itself like so:

  1. user types a
  2. get/render response for a
  3. user types ab
  4. user types abc
  5. get/render response for abc
  6. get/render response for ab

This could happen for many reasons:

  • An ISP could have directed the abc query through a less-congested router,
  • abc could have had fewer possible answers, resulting in a faster query.

Regardless of the reason, our user now has the wrong results in front of them. How can you prevent this terrible tragedy?

Preventing Race Conditions

Back in the days of VanillaJS, a solution might have started off based on an event listener: addEventListener.

addEventListener

Get hands-on with 1400+ tech skills courses.