Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an example of when I don't need to handle unsubscribing in the component?

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?

like image 808
calbear47 Avatar asked Dec 05 '18 17:12

calbear47


People also ask

What happens if you don't unsubscribe from an observable?

🎩 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…

Do we need to unsubscribe from observable?

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.

Do I need to unsubscribe from router events?

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.

Do we need to unsubscribe http calls?

There is no need to unsubscribe from HttpClient observables as they are finite observables, i.e. they complete after emitting a value.


1 Answers

Short answer

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.

like image 190
erhise Avatar answered Sep 27 '22 21:09

erhise