Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2191
隐瞒了意图╮
隐瞒了意图╮ 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:27

    Based on : Using Class inheritance to hook to Angular 2 component lifecycle

    Another generic approach:

    export abstract class UnsubscribeOnDestroy implements OnDestroy {
      protected d$: Subject;
    
      constructor() {
        this.d$ = new Subject();
    
        const f = this.ngOnDestroy;
        this.ngOnDestroy = () => {
          f();
          this.d$.next();
          this.d$.complete();
        };
      }
    
      public ngOnDestroy() {
        // no-op
      }
    
    }

    And use :

    @Component({
        selector: 'my-comp',
        template: ``
    })
    export class RsvpFormSaveComponent extends UnsubscribeOnDestroy implements OnInit {
    
        constructor() {
            super();
        }
    
        ngOnInit(): void {
          Observable.of('bla')
          .takeUntil(this.d$)
          .subscribe(val => console.log(val));
        }
    }

提交回复
热议问题