Angular/RxJs When should I unsubscribe from `Subscription`

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

    --- Update Angular 9 and Rxjs 6 Solution

    1. Using unsubscribe at ngDestroy lifecycle of Angular Component
    class SampleComponent implements OnInit, OnDestroy {
      private subscriptions: Subscription;
      private sampleObservable$: Observable;
    
      constructor () {}
    
      ngOnInit(){
        this.subscriptions = this.sampleObservable$.subscribe( ... );
      }
    
      ngOnDestroy() {
        this.subscriptions.unsubscribe();
      }
    }
    
    1. Using takeUntil in Rxjs
    class SampleComponent implements OnInit, OnDestroy {
      private unsubscribe$: new Subject;
      private sampleObservable$: Observable;
    
      constructor () {}
    
      ngOnInit(){
        this.subscriptions = this.sampleObservable$
        .pipe(takeUntil(this.unsubscribe$))
        .subscribe( ... );
      }
    
      ngOnDestroy() {
        this.unsubscribe$.next();
        this.unsubscribe$.complete();
      }
    }
    
    1. for some action that you call at ngOnInit that just happen only one time when component init.
    class SampleComponent implements OnInit {
    
      private sampleObservable$: Observable;
    
      constructor () {}
    
      ngOnInit(){
        this.subscriptions = this.sampleObservable$
        .pipe(take(1))
        .subscribe( ... );
      }
    }
    

    We also have async pipe. But, this one use on the template (not in Angular component).

提交回复
热议问题