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 matter | mergeMap |
| preserve the order, queue them up | concatMap |
| cancel the stale one, take the latest | switchMap |
| ignore the new while busy | exhaustMap |
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
- Inside the function in
map, build a mapping object:parallel → mergeMap,queue → concatMap,latest → switchMap,busy → exhaustMap. - Return the string
item.name + ': ' + operatorByStrategy[item.strategy]. - 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
CONSOLE · Console output
Hit Run to see the result...