Performance: mergeMap vs concatMap vs exhaustMap
This concept affects how asynchronous streams are handled, impacting UI responsiveness and interaction delays.
source$.pipe(mergeMap(() => httpRequest$, 4)).subscribe();source$.pipe(concatMap(() => httpRequest$)).subscribe();
| Pattern | Concurrency | Order Guarantee | Impact on INP | Verdict |
|---|---|---|---|---|
| mergeMap | High (all concurrent) | No | Can cause race conditions and overload | [!] OK |
| concatMap | One at a time | Yes | May delay input responsiveness due to queuing | [!] OK |
| exhaustMap | One at a time, ignores new while active | No | Prevents overload, improves stability | [OK] Good |
mergeMap behaviormergeMap subscribes to all inner observables immediately and merges their outputs as they arrive.concatMap waits for each inner observable to complete before starting the next, exhaustMap ignores new inner observables if one is active, and switchMap cancels previous inner observables.concatMap in an Angular RxJS pipe?concatMap are used inside pipe() method on observables.source$.pipe(concatMap(...)). Options A and B misuse method chaining or function call. source$.pipe(map(concatMap(value => inner$))) wrongly nests concatMap inside map.import { of } from 'rxjs';
import { concatMap, delay } from 'rxjs/operators';
of(1, 2, 3).pipe(
concatMap(x => of(x).pipe(delay(100 - x * 10)))
).subscribe(console.log);concatMap waits for each inner observable to complete before starting the next, preserving order.exhaustMap. It should ignore new clicks while processing, but it processes all clicks anyway. What is the likely mistake?
buttonClicks$.pipe( exhaustMap(() => fetchData()) ).subscribe();
exhaustMap expects the function to return an observable. If fetchData() returns a promise, it won't behave correctly.searchInput$.pipe( ???(query => performSearch(query)) ).subscribe(results => display(results));
exhaustMap ignores new inner observables if one is active, perfect for this use case. mergeMap runs all, concatMap queues, switchMap cancels previous.Pass the test and this pattern moves unknown