Delete subscription in observer

956 Views Asked by At

I have created a canDeactivate handler for my Angular 4 form. Although this works, I fear that I am causing a memory leak (for lack of a better term). I read that you must unsubscribe to avoid an ever growing list of subscriptions; but I'm not sure where/how to unsubscribe from the subscription I create below. Does the observer.complete call delete the subscription?

  // Allow the user to navigate away from this page
  public canDeactivate(): Observable<boolean> {

    // Popup a prompt dialog
    const title = 'Lose Changes';
    const prompt = 'Are you sure you want to lose your changes?';
    this.dialogWindow.show(EDialogTypes.EDialogYesNo, EDialogStyles.EDialogStyleWarning, title, prompt);

    return Observable.create(observer => {
      this.dialogWindow.observable.subscribe(buttonPressed => {
        const proceed = (buttonPressed === EButtonPressed.EButtonPressedYes);
        console.log('Allow proceed: ' + proceed);
        observer.next(proceed);
        observer.complete();
      });
    });
  }
1

There are 1 best solutions below

0
On BEST ANSWER

You can save the subscription to a variable and use it to unsubscribe after getting what you need. Something like this:

return Observable.create(observer => {
  let subscription = this.dialogWindow.observable.subscribe(buttonPressed => {
    const proceed = (buttonPressed === EButtonPressed.EButtonPressedYes);
    console.log('Allow proceed: ' + proceed);
    observer.next(proceed);
    observer.complete()
    subscription.unsubscribe(); // here you unsubscribe
  });
});