Skip to content

Instantly share code, notes, and snippets.

@marcelaraujo
Last active December 13, 2018 01:53
Show Gist options
  • Save marcelaraujo/f13cfd4b029d789e25831bc4ff094768 to your computer and use it in GitHub Desktop.
Save marcelaraujo/f13cfd4b029d789e25831bc4ff094768 to your computer and use it in GitHub Desktop.
RxJS
There are multiple flattening strategies for observables:
With mergeMap (which has flatMap as an alias), received observables are subscribed to concurrently and their emitted values are flattened into the output stream.
With concatMap, received observables are queued and are subscribed to one after the other, as each completes. (concatMap is mergeMap with a concurrency of one.)
With switchMap, when an observable is received it's subscribed to and any subscription to a previously received observable is unsubscribed.
With exhaustMap, when an observable is received it's subscribed to unless there is a subscription to a previously received observable and that observable has not yet completed - in which case the received observable is ignored.
The concatAll, exhaust, mergeAll and switchAll operators for higher-order observables are implemented using the *Map operators.
---------------------------------------------------------------------------------------------------------------------
To summarise, when you need to use a flattening operator in an effect/epic you should:
use concatMap with actions that should be neither aborted nor ignored and for which the ordering must be preserved — it’s also a conservative choice that will always behave in a predictable manner;
use mergeMap with actions that should be neither aborted nor ignored and for which the ordering is unimportant;
use switchMap with read actions that should be aborted when another action of the same type is dispatched; and
use exhaustMap with actions that should be ignored whilst an action of the same type is pending.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment