map vs switchMap in RxJS

前端 未结 4 2000
甜味超标
甜味超标 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:05

    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));
    

提交回复
热议问题