0

Unable to unsubscribe on a subscription if used in a public method and not ngOnDestroy.

If have rxjs observable interval that is used to poll an API. onNgInit I subscribe to that observable as follows:

Class .. {
   pollingSubscription: Subscription;

  ngOnInit() {
      startPolling();
  } 

  // when this gets triggered my polling subscription stops
  ngOnDestroy() {
      if (this.pollingSubscribe) {
          this.pollingSubscription.unsubscribe();
      }
  }

   startPolling() {
      const pollingInterval: Observable<any> = observable.interval(3000).startWith(0);
      this.pollingSubscription = pollingInterval.subscribe( _ => {
         this.store.dispatch(// trigger my Action);
      });
   }

   // when this gets triggered on a click event my polling subscription still keeps polling.
   stopPolling() {
       if ( // condition true) {
           // on this condition stop polling, FYI this line does get triggered,
           // but there is no effect, it still keeps subscribed.
           this.pollingSubscription.unsubscribe();
       }
   }
}

Is there anything wrong that I doing, in the public function stopPolling(). How do I unsubscribe on a condition while still active on a given component.

Thanks.

patz
  • 1,306
  • 4
  • 25
  • 42

1 Answers1

0

Did your class uses implements OnInit, OnDestroy ?? may be if your class is not implemented using OnDestroy then ngOnDestroy() will not be executed. This is the official link for OnDestroy

The following snippet shows how a component can implement this interface to define its own custom clean-up method.

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
    ngOnDestroy() {
       // ...
    }
}
Nasiruddin Saiyed
  • 1,438
  • 1
  • 13
  • 31