Angular:我应该退订switchMap吗

时间:2019-10-23 10:25:31

标签: angular rxjs

我有以下组件:

@Component({...})
export class AppComponent implements OnInit, OnDestroy {

  destroy$ = new Subject();
  update$ = new Subject();

  result: Result;

  constructor(service: Service) {
  }

  ngOnInit() {
    update$.pipe(
      takeUntil(this.destroy$),
      switchMap(() => this.service.get())
    ).subscribe(result => this.result = result);

    this.refresh();
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  refresh() {
    this.update$.next();
  }

}

这种方法正确吗?还是应该在takeUntil(this.destroy$)之后致电switchMap

update$.pipe(
  switchMap(() => this.service.get()),
  takeUntil(this.destroy$)
).subscribe(result => this.result = result);

还是我应该打两次?

update$.pipe(
  takeUntil(this.destroy$),
  switchMap(() => this.service.get()),
  takeUntil(this.destroy$)
).subscribe(result => this.result = result);

2 个答案:

答案 0 :(得分:4)

最干净的方法是在takeUntil之后调用switchMap

update$.pipe(
  switchMap(() => this.service.get()),
  takeUntil(this.destroy$)
).subscribe(result => this.result = result);

这将防止订阅产生任何排放。如果您之前添加了takeUntil,则switchMap订阅将发出值,直到project函数返回的可观察值完成为止,这可能永远不会发生(取决于您的服务代码)。

takeUntil之前和之后都不需要调用switchMap,因为switchMap本身可以取消订阅时,可以从源中取消订阅(switchMap之前的所有内容)来自。

答案 1 :(得分:0)

通常,您希望takeUntil应该是最后一个运算符。在您的情况下,这是正确的方法:

update$.pipe(
  switchMap(() => this.service.get()),
  takeUntil(this.destroy$)
).subscribe(result => this.result = result);
相关问题