map vs switchMap in RxJS

前端 未结 4 1960
甜味超标
甜味超标 2021-01-18 06:48

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?

4条回答
  •  被撕碎了的回忆
    2021-01-18 07:10

    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.

提交回复
热议问题