When should I store the Subscription
instances and invoke unsubscribe()
during the NgOnDestroy life cycle and when can I simply ignore them?
--- Update Angular 9 and Rxjs 6 Solution
unsubscribe
at ngDestroy
lifecycle of Angular Componentclass SampleComponent implements OnInit, OnDestroy {
private subscriptions: Subscription;
private sampleObservable$: Observable;
constructor () {}
ngOnInit(){
this.subscriptions = this.sampleObservable$.subscribe( ... );
}
ngOnDestroy() {
this.subscriptions.unsubscribe();
}
}
takeUntil
in Rxjsclass 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();
}
}
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).