首页 > 解决方案 > switchMap 到 switchMapTo

问题描述

目前我有这段代码

this.save()
  .pipe(switchMap(() => this.unlock()))
  .subscribe(...);

saveunlock实现是

private save(): Observable<void> {
  return new Observable(subscriber => {
    this.xmlService.save(..., () => {
      ...       
      subscriber.next();
      subscriber.complete();
    });
  });
}

private unlock(): Observable<void> {
  return this.httpService.unlock(this.id);
}

由于这unlock并不真正依赖于价值save回报,我可以使用switchMapTo吗?

this.save()
  .pipe(switchMapTo(this.unlock()))
  .subscribe(...);

还是我误解了*To变体的行为方式?

标签: typescriptrxjs

解决方案


switchMapToswitchMap除了它需要一个可观察的而不是回调函数之外,它是相同的。查看源代码:

https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/switchMapTo.ts#L56


推荐阅读