Do I need to `complete()` takeUntil Subject inside ngOnDestroy?

后端 未结 3 1456
北荒
北荒 2020-12-09 23:18

To avoid Observable memory leaks inside Components, I am using takeUntil() operator before subscribing to Observable.

I write something like this inside

3条回答
  •  不思量自难忘°
    2020-12-09 23:49

    You only need to unsubscribe like:

    subscr: Subscription;
    
    ngOnInit() {
      this.subscr = this.http
        .get('test')
        .pipe(takeUntil(this.unsubscribe$))
        .subscribe(x => console.log(x));
    }
    
    ngOnDestroy() {
      this.subscr.unsubscribe();
    }
    

    To unsubscribe using takeUntil():

    The solution is to compose our subscriptions with the takeUntil operator and use a subject that emits a truthy value in the ngOnDestroy:

    export class AppComponent implements OnInit, OnDestroy {
      destroy$: Subject = new Subject();
    
      ngOnInit() {
       this.http
        .get('test')
        .pipe(takeUntil(this.unsubscribe$))
        .subscribe(x => console.log(x));
      }
    
      ngOnDestroy() {
        this.destroy$.next(true);
      }
    }
    

    Note that using an operator like takeUntil instead of manually unsubscribing will also complete the observable, triggering any completion event on the observable.

    See here

提交回复
热议问题