javascript – what is the best way to unsubscribe of function in method?


Working on dialog component with angular js and now I find out that my function is subscribed and in if condition do not quit method, but continuously executing another function afterClosed() , here is example of code :

  openCreateNewContentDialog(): void {
    const oldData = this.dataSource.data;
    const dialogConfig = AppConstants.matDialogConfig();
    const dialog = this.dialog.open(LicenseDialogComponent, dialogConfig);

    dialog.beforeClosed().subscribe(licenceDate => {
      for (const datesToCheck of oldData) {
        const newDateFrom = new Date(licenceDate.expirationDateFrom);
        const oldDateTo = new Date(datesToCheck.expirationDateTo.toString());
        if (newDateFrom <= oldDateTo) {
          // console.log('return?');
          return;
        }
      }
    });

    dialog.afterClosed().subscribe(licence => {
      if (licence) {
        this._value.push(licence);
        this.dataSource.data = this.value;
        this.change();
      }
    });
  }

What is the best and optimized way to unsubscribe beforeClosed() function?