Thursday, November 29, 2018

flatMap, mergeMap, switchMap, concatMap, which one !?

To concatenate(or chain) asynchronous tasks we can just use then method of Promise, as example from javascript document

const promise = doSomething();
const promise2 = promise.then(successCallback, failureCallback)



Instead in the never ending story of  Observable world, chaining becomes not much easy as to line up for tickets, but more like a pipeline of factory. each pipe function waits for the incoming data, do something to it, and pass to next pipe function.

The default pipe method of Observable, coupled with some rxjs operators like tap and map, profoundly cover this chaining scenario. There is a tricky thing for one situation: what if one of the task need to wait for another Observable, rxjs provide four recipes: flatMap、mergeMap、switchMap、concatMap.

Overall, they all expect you to transfer from one observable to another, but the difference between them are...

switchMap will cancel the previous observable and subscribe to the new observable, makes it only one subscription active at the same time.

concatMap waits only for the previous observable to complete, then it subscribe to the next observable, so be cautious with observables which don't complete.

mergeMap allows for multiple inner subscriptions to be active at the same time, contrast to switchMap, so mergeMap is better for requests that shoud not be canceled

flatMap actually ... is an alias ... of  ... mergeMap

No comments:

Post a Comment