BACK
Lessons27. How to choose a flattening operator
Lessons · 27

27. How to choose a flattening operator

Consolidation: the decision map

Now that you've seen all four flattening operators in action, the important skill is choosing the right one from the business rule. This lesson is a recognition exercise.

Cheat sheet

If you need to... Operator
run tasks in parallel, order doesn't mattermergeMap
preserve the order, queue them upconcatMap
cancel the stale one, take the latestswitchMap
ignore the new while busyexhaustMap

The choosing principle

There's no "best" operator. There's the operator that exactly describes the behavior the business needs. Always answer one question: "what should happen if a new value arrives while the old one is still running?"

Your task

  1. Inside the function in map, build a mapping object: parallel → mergeMap, queue → concatMap, latest → switchMap, busy → exhaustMap.
  2. Return the string item.name + ': ' + operatorByStrategy[item.strategy].
  3. Expected output: parallel uploads: mergeMap → ordered saves: concatMap → typeahead search: switchMap → login button: exhaustMap.
Solution spoiler · click to reveal
const { from, map } = Rx;

const scenarios = [
  { name: 'parallel uploads', strategy: 'parallel' },
  { name: 'ordered saves', strategy: 'queue' },
  { name: 'typeahead search', strategy: 'latest' },
  { name: 'login button', strategy: 'busy' },
];

const result$ = from(scenarios).pipe(
  map(item => {
    const operatorByStrategy = {
      parallel: 'mergeMap',
      queue: 'concatMap',
      latest: 'switchMap',
      busy: 'exhaustMap',
    };

    return item.name + ': ' + operatorByStrategy[item.strategy];
  })
);

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