简体   繁体   中英

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?

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.

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.

So, if you want the entire stream to be unsubscribed, just place a takeUntil at the end of the main (outer) stream. But if you want a specific inner observable to complete only when a specific observable emits, you'll have to add takeUntil only there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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