0
votes

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.

1
where are you making the functional call to stopPolling()?Anjil Dhamala
its just an example, it can be called anywhere, like a click event.patz
I asked because I did not see the functional call where the subscription is unsubscribed from.Anjil Dhamala
@patz are you sure the condition is true? there is nothing wrong with the code, it should unsubscribe without a problemggradnig
Well, I'm not sure what's different in your code, but I've reconstructed it on StackBlitz and can't find any problem: stackblitz.com/edit/…ggradnig

1 Answers

0
votes

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() {
       // ...
    }
}