RxJS 5中flatMap、mergeMap、switchMap、concatMap的区别(Angular视角)
SwitchMap vs FlatMap (MergeMap) vs ConcatMap in Angular (RxJS 5)
Hey there! Let's break this down clearly, starting with your existing understanding—you're mostly spot on, but there's a small key clarification needed around FlatMap.
Your Existing Understanding: A Quick Validation
- SwitchMap: You nailed this! SwitchMap cancels any ongoing inner Observable the moment a new value comes from the outer Observable, only emitting values from the latest inner stream. This is perfect for use cases like search input debouncing, where you only care about results from the most recent search term and want to ignore stale pending requests.
- FlatMap: Here's the tweak: in RxJS 5+, FlatMap is just an alias for MergeMap! Your description of "collect all independent Observables, emit all their values asynchronously without strict order" is exactly how MergeMap works—you were already describing MergeMap without realizing FlatMap is the same function. One small correction though: it doesn't return values in an array; it emits each value individually as soon as the inner Observable produces it.
- ConcatMap: You got this 100% right! ConcatMap runs inner Observables sequentially, waiting for each one to fully complete before starting the next. It strictly preserves the order of the outer Observable's emissions, so output values match the order they were triggered. This is ideal for things like sequential API calls where the order of operations matters (e.g., creating a user first, then fetching their profile).
How MergeMap (aka FlatMap) Works
MergeMap takes each value emitted by the outer Observable, maps it to an inner Observable, then merges all those inner streams into a single output Observable. Let's break down its core behavior:
- No cancellation: All inner Observables run concurrently (by default—you can set a concurrency limit if needed) and are allowed to complete.
- Emits values as they arrive: The output order doesn't guarantee matching the outer Observable's emission order. For example: if the outer Observable emits
1(which maps to an inner stream that takes 1 second to emit a value) and then immediately emits2(which maps to an inner stream that takes 0.5 seconds), the output will be2first, then1. - FlatMap = MergeMap: Remember, these are identical in RxJS 5—FlatMap is just an older name that's still supported for compatibility.
Quick Cheat Sheet for Use Cases
- SwitchMap: Use when you only care about the latest inner stream results (e.g., search inputs, live filters)
- MergeMap/FlatMap: Use for independent asynchronous operations where order doesn't matter (e.g., fetching multiple unrelated resources at once)
- ConcatMap: Use when you need to preserve execution order and run operations sequentially (e.g., ordered API workflows)
内容的提问来源于stack exchange,提问作者xkeshav
相关产品推荐
相关产品推荐

