Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - DialogRef - Unsubscribe - Do I need to unsubscribe from afterClosed?

I got asked by one of my colleagues if we need to unsubscribe from the afterClosed() Observable of a Dialog.

We are using the takeUntil pattern to unsubscribe from all Observables on ngOnDestroy().

this.backEvent = fromEvent(window, 'popstate')     .pipe(         takeUntil(this.destroy$)     )     .subscribe(         () => {             this.navigationService.backClicked = true;             this.navigationService.navigateBackToDirectoryCenter();         }     ); 

ngOnDestroy()

ngOnDestroy() {     this.destroy$.next();     this.destroy$.complete(); } 

So is it necessary to unsubscribe from afterClosed() Observable?

dialogRef.afterClosed().subscribe(     (data) => {             console.log(data);         }     }, ); 

or?

dialogRef.afterClosed()     .pipe(         takeUntil(this.destroy$)     )     .subscribe(         (data) => {             console.log(data);         },     ); 
like image 232
liqSTAR Avatar asked Oct 02 '19 09:10

liqSTAR


People also ask

Do we need to unsubscribe subject in angular?

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

What happens if we don't unsubscribe in angular?

Specifically, we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.

Does angular unsubscribe automatically?

@YoussefTaghlabi, FYI, the official angular documentation (angular.io/guide/http) does mention that: "The AsyncPipe subscribes (and unsubscribes) for you automatically." So, it's indeed officially documented.


1 Answers

No

You don't need to unsubscribe as the observable itself completes.You can verify the same by adding a finalize block to see whether observable completes itself or not.

import { finalize } from "rxjs/operators"; 
dialogRef   .afterClosed()   .pipe(finalize(() => console.log("completed")))   .subscribe(data => {     console.log(data);   });  

And when you will close the dialog, you will see completed in console, this depicts that you do not need to unsubscribe the observable.

like image 98
Archit Garg Avatar answered Sep 19 '22 09:09

Archit Garg