map vs switchMap in RxJS

ε祈祈猫儿з 提交于 2020-11-29 04:34:31

问题


I read the documentation of switchMap and map, but I still don't completely understand the difference. Are there some cases where it does not make a difference at all?


回答1:


Both operators are different.

switchMap: Maps values to observable. Cancels the previous inner observable.

Eg:

fromEvent(document, 'click')
  .pipe(
    // restart counter on every click
    // First click: 0, 1, 2...
    // Second click: cancels the previous interval and starts new one. 0, 1, 2...
    switchMap(() => interval(1000))
  )
  .subscribe(console.log);

map: Add projection with each value.

Eg:

//add 10 to each value
const example = source.pipe(map(val => val + 10));



回答2:


Are there some cases where it does not make a difference at all?

No. They are two totally different beasts. switchMap is expected to return an observable, map can return anything. Their application is different. It would typically go like this:

someStream$.pipe(
    switchMap(args => makeApiCall(args)), // must return a stream
    map(response => process(response)) // returns a value of any shape, usually an object or a primitive
).subscribe(doSomethingWithResults);

There are other operators similar in nature to switchMap: mergeMap (AKA flatMap), exhaustMap, concatMap (and there are cases when all those amount to more or less the same thing), but not map.




回答3:


Instead of a textual explanation, I always prefer visual explanation.

Map -

switchmap -




回答4:


see the definitions of 2 functions:

map<inputType, outputType>(syncFunction: (input: inputType) => outputType )

switchmap<inputType, Observable<outputType>>( asyncFunction: (input: inputType) =>  Observable<outputType> )

map = an asynchronous function calls a synchronous function (asyncTask => syncTask)

switchMap = an asynchronous function calls an asynchronous function sequentially (asyncTask => asyncTask )

example for switchMap:

  observable1 calls observable2 means:
        observable1_event1 => new observable2 asynchronous => Task1
        observable1_event2 => new observable2 asynchronous => Task2
        observable1_event3 ...

If observable1_event2 is emitted when task1 is not completed, the Observable2 of task1 will be rejected by calling unsubscribe(). It means Task1 will not show output any more after that.

If observable1_event2 is emmitted when task1 was completed. all outputs of Task1 will be showed normally then outputs of task2 will be showed.

Note that: each new observable2 can trigger many events (observable2_event1, observable2_event2,...)



来源:https://stackoverflow.com/questions/57903624/map-vs-switchmap-in-rxjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!