忽略switchMap返回值

时间:2018-02-22 22:21:55

标签: rxjs

我想解析一个observable,但我不希望返回值替换管道中的前一个值。有异步tap()吗?我需要像switchMap这样的运算符,但我想忽略返回。

of(1).pipe(switchMap(() => of(2))).subscribe(console.log); // expected: 1

我可以创建一个自定义运算符,但确定rxjs中内置了一些内容。

4 个答案:

答案 0 :(得分:5)

我最终得到了这个自定义运算符。它就像点击但解析了observable(并且应该更新以支持promises)。

export function switchTap<T, R>(next: (x: T) => Observable<R>): MonoTypeOperatorFunction<T>;
export function switchTap<R>(observable: Observable<R>): MonoTypeOperatorFunction<R>;
export function switchTap<T, R>(
  arg: Observable<T> | ((x: T) => Observable<R>)
): MonoTypeOperatorFunction<T> {
  const next: (x: any) => Observable<T | R> =
    typeof arg === 'function' ? arg : (x: any): Observable<T> => arg;
  return switchMap<T, T>(value => next(value).pipe(ignoreElements(), concat(of(value))));
}

用法:

of(1).pipe(switchTap(of(2))).subscribe(console.log) // 1

或使用函数:

of(1)
      .pipe(
        switchTap(value => {
          console.log(value); // value: 1
          return of(value + 1);
        })
      )
      .subscribe(console.log); // 1

答案 1 :(得分:1)

如果您只是想忽略订阅的值,那么就不要传递subscribe回调中的任何参数:

of(1).pipe(switchMap(() => of(2))).subscribe(()=>{
    console.log('no arguments')
});

如果你想保留第一个observable的值,那么事情就会变得棘手。一种方法是使用Subject来保留值:

//create a BehaviorSubject
var cache = new BehaviorSubject<any>(0);

of(1).pipe(switchMap((first) => {
    cache.next(first);
    return of(2);
})).subscribe(() => {
    console.log(cache.value) //gives 1
});

或者您可以使用.map()来更改值。这有点hacky,代码更难维护:

of(1).pipe(switchMap((first) => {
    return of(2).map(() => first);
})).subscribe((second) => {
    console.log(second) //gives 1 because the values was mapped
});

答案 2 :(得分:0)

我这样做

of(2).pipe(
   switchMap( num => this.doSmtg(num), num => num)
).subscribe(num => console.log(num)); // 2

switchmap的第二个参数接收两个值,一个传递给this.doSmtg,另一个是doSmtg(num)的observable返回的值。

答案 3 :(得分:0)

对于任何有相同问题的新手,我建议使用resultSelector和其他RxJS映射运算符支持的switchMap参数。

示例:

switchMap(1 => of(2), (one, two) => one)

进一步阅读:https://www.learnrxjs.io/operators/transformation/mergemap.html