I've become accustomed to unsubscribing to subscriptions I initialize in my components. The recommended approach is to use the takeUntil
operator like so:
killSubscriptions: new Subject<any> = new Subject();
ngOnInit(){
observableThing().pipe(takeUntil(this.killSubscriptions)).subscribe()
}
ngOnDestroy(){
this.killSubscriptions.next();
this.killSubscriptions.complete();
}
But then I was implementing a custom dialog with the overlay & portal service the other day, and I came across this block of code in the middle of a method in the Angular Material Library.
// When the dialog backdrop is clicked, we want to close it.
if (config.hasBackdrop) {
overlayRef.backdropClick().subscribe(() => {
if (!dialogRef.disableClose) {
dialogRef.close();
}
});
}
How is this subscription cleaned up? My only guess is when the overlayRef
is disposed, the subscription is cleaned up. But how?
Are there other times we don't need to handle unsubscription?
🎩 Automagically Unsubscribe in Angular As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak. A memory leak occurs when a section of memory that is no longer being…
In Angular applications, it's always recommended to unsubscribe the observables to gain benefits like: Avoids Memory Leaks. Aborting HTTP requests to avoid unwanted calls.
Generally you do not need to unsubscribe from HTTP calls. The ActivatedRoute and its observables are insulated from the Router itself so the Angular Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.
There is no need to unsubscribe from HttpClient observables as they are finite observables, i.e. they complete after emitting a value.
Because they complete the observer when the OverlayRef is considered going into dispose state.
this._backdropClick.complete();
Angular Material CDK source code
Hope this helps! Going through the source code and trying to understand it is a good and fun way to learn :)
Edit: If you are not sure that your observer will complete then you need to make sure you actively unsubscribe to avoid memory leakage. Your takeUntil pattern is one way to go. You can even change the type from any
to void
on your Subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With