RxJS is a powerful reactive programming library that focuses on the use of Observables. It provides developers with a variety of tools, including many types of operators. This read will explore some of the most common and useful transformation operators RxJS offers.
mergeMap()
The mergeMap() transformation operator maps each value to an observable and then flattens the observables by subscribing internally, emitting the results; mergeMap() flattens the inner observable as they occur.
Each time the source observable emits a value, the function you supply to mergeMap() is invoked. The observable returned by this function is then subscribed to internally. From that point forward, whenever the inner observable emits a value, mergeMap() also emits that value.
There are unlimited inner observables, so remember to clean up these inner observables to avoid memory leaks (i.e. use take() or takeUntil()).
switchMap()
The switchMap() operator waits for the previous Observable to complete before creating the next one. Only maintains 1 active subscription at a time. Switch to a new observable on emissions.
This is the safest operator for flattening. It is harder to create leaks than using mergeMap(). It is best to avoid switchMap() when it's cancellation could have undesired effects (i.e. saves/POST).
concatMap()
The concatMap() operator maps each value to an observable and then flattens the results. All inner observables are queued and subscribed to in order until the previous completes.
Note: concatMap() is equivalent to mergeMap with concurrency parameter set to 1.
exhaustMap()
The exhaustMap() operator ignores emissions when an inner observable is active.
Final thoughts
RxJS provides developers with many tools to control and mitigate reactive programming, some of which are transformation operators. We hope you enjoyed taking a deeper dive into what RxJS has to offer and hope you follow us on Twitter and Linkedin to stay updated with new content.
Tevpro is a custom software development firm founded in Houston, Texas. We'd love to work with you or help answer any questions.