BACK
PracticeReal-life: switchMap() cancel a stale request
PRACTICE · 73 · 練

Real-life: switchMap() cancel a stale request

Two queries arrive at once and the response is async. Only the last query, ab, should remain.

  1. Solve the task in the editor — no long theory.
  2. Run the check and compare your output with the expected result.
  3. Stuck? Open the solution and carry the approach into your own code.
Solution spoiler · click to reveal
const { of, timer, switchMap, map } = Rx;

const search = query => timer(0).pipe(map(() => query));

const result$ = of('a', 'ab').pipe(
  switchMap(query => search(query))
);

result$.subscribe(value => console.log(value));
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...