31

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);
        },
    );
liqSTAR
  • 828
  • 7
  • 19

2 Answers2

57

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.

Community
  • 1
  • 1
Archit Garg
  • 1,760
  • 8
  • 18
4

Good question, just had a look at the docs (https://material.angular.io/components/dialog/overview) , nothing seems to hint towards the need to unsubscribe at all, what you already have should suffice.