My top 6 ‘Similar, but different’ RxJS operators
Sharing my top 6 ‘Similar, but different’ RxJS operators
Introduction
RxJS offers many operators to process data. Definitely, it’s a good thing, however, it can get confusing to choose the right operator in a particular case. So, If you’re not familiar with RxJS this may lead you to use the wrong operator.
In this post, I’m going to share my top 6 common ‘similar but different’ RxJS operators to help you save time by avoiding them.
single(), take(1) and first()
first(): Emits only the first value (or the first value that meets some condition) emitted by the source Observable or emits an error if the upstream is empty.
take(1): Limits the number of upstream items to 1 and no errors are emitted if the upstream is empty.
single(): Make sure upstream isn’t empty.
To sum up, we can say thatfirst == take(1).single()
where take(1)
limits the number of upstream items to 1 and single()
makes sure upstream isn't empty.
map() vs switchAll() vs switchMap()
map(): Apply a projection to each value and emit that projection in the output Observable.
switchAll(): Takes a higher-order observable and subscribes to the most recently provided inner observable and unsubscribes the previously subscribed one.
switchMap(): Is the combination of map()
and switchAll()
.
zip() vs combineLatest() vs forkJoin()
zip(): Take a group of observables, Wait until all observables have emitted a value then emit all as an array.
combineLatest(): Like the zip()
, combineLatest()
will wait until all observables have emitted a value as an array. From there, it will emit an array each time one observable emits a value.
forkJoin(): Take a group of Observables, wait for them to complete emission and emit the final value of each Observable as an array.
merge() vs mergeAll() vs mergeMap()
merge(): Take a group of observables, and flatten them within one, so whenever any observable emits a value, the output will emit a value.
mergeAll(): Merge a group of inner observables emitted by one higher-order observable, and flatten them into one first-order output observable.
mergeMap(): Is the combination of map()
and mergeAll()
.
concat() vs concatAll() vs concatMap()
The same thing as merge()
, mergeAll()
and mergeMap()
, except that with concat the Observable must complete before the next one starts emitting values.
window() vs buffer()
buffer(): Cache values emitted by an Observable and emit them as an array when the notifier
emits.
window(): Subdivides the items from an Observable into nested Observables when the windowBoundaries
emits.
Conclusion
Finally, Rx is a huge library that can help you handle complex asynchronous aspects of your application. In this post, I tried to clarify commonly used operators and group them by similarity.