简体   繁体   English

在每个 pipe 中使用 takeUntil 是一个多余的步骤吗?

[英]Using takeUntil in each pipe is a redundant step?

I just wonder if using takeUntil in each pipe is the best practice or only one for the whole?我只是想知道在每个 pipe 中使用takeUntil是最佳实践还是只有一个?

search = (text$: Observable<string>) =>
text$.pipe(
  debounceTime(200),
  distinctUntilChanged(),
  filter((term) => term.length >= 2),
  tap(() => (this.searching = true)),
  switchMap((term) =>
    this.searchService.search(term).pipe(
      catchError(() => {
        this.searchFailed = true;
        return of([]);
      }),
      takeUntil(this._destroy$)
    )
  ),
  tap(() => (this.searching = false)),
  takeUntil(this._destroy$)
);

I'd say it depends on what you want to achieve.我会说这取决于你想要达到的目标。

If you only use the last takeUntil , when its observable emits, the entire stream will be unsubscribed.如果你只使用最后一个takeUntil ,当它的 observable 发射时,整个 stream 将被取消订阅。

If you only use the takeUntil from switchMap 's callback, then if it emits, only the switchMap 's inner observable will be unsubscribed, but not the entire stream.如果你只使用takeUntil回调中的switchMap ,那么如果它发出,则只有switchMap的内部 observable 将被取消订阅,而不是整个 stream。

So, if you want the entire stream to be unsubscribed, just place a takeUntil at the end of the main (outer) stream.因此,如果您希望取消订阅整个 stream,只需在(外部)stream 的末尾放置一个takeUntil But if you want a specific inner observable to complete only when a specific observable emits, you'll have to add takeUntil only there.但是,如果您希望特定的内部 observable 仅在特定的 observable 发出时完成,则必须在此处添加takeUntil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM