Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2717
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 04:56

When should I store the Subscription instances and invoke unsubscribe() during the NgOnDestroy life cycle and when can I simply ignore them?

22条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 05:29

    In case unsubscribe is needed the following operator for observable pipe method can be used

    import { Observable, Subject } from 'rxjs';
    import { takeUntil } from 'rxjs/operators';
    import { OnDestroy } from '@angular/core';
    
    export const takeUntilDestroyed = (componentInstance: OnDestroy) => (observable: Observable) => {
      const subjectPropertyName = '__takeUntilDestroySubject__';
      const originalOnDestroy = componentInstance.ngOnDestroy;
      const componentSubject = componentInstance[subjectPropertyName] as Subject || new Subject();
    
      componentInstance.ngOnDestroy = (...args) => {
        originalOnDestroy.apply(componentInstance, args);
        componentSubject.next(true);
        componentSubject.complete();
      };
    
      return observable.pipe(takeUntil(componentSubject));
    };
    

    it can be used like this:

    import { Component, OnDestroy, OnInit } from '@angular/core';
    import { Observable } from 'rxjs';
    
    @Component({ template: '
    ' }) export class SomeComponent implements OnInit, OnDestroy { ngOnInit(): void { const observable = Observable.create(observer => { observer.next('Hello'); }); observable .pipe(takeUntilDestroyed(this)) .subscribe(val => console.log(val)); } ngOnDestroy(): void { } }

    The operator wraps ngOnDestroy method of component.

    Important: the operator should be the last one in observable pipe.

提交回复
热议问题