Jono
Jono

Reputation: 143

How to destroy an observable

I have established an observable in my service in order to poll for updates from an API every 2 seconds; the observable is persisting but I need to destroy it when I move pages or make a call for a different result.

Can anyone help in how to destroy the observable either on page exit or as a manual request (e.g. from another call to the API)?

return Observable.interval(2000).switchMap(() => {
  return super.doRequest('/audit/api/' + this.API_version + '/Query/GetFlowHistory?sagaId=' + sagaId, 'get', {}).map((responseData) => {

    return responseData
  }); })

Upvotes: 3

Views: 6741

Answers (1)

alt255
alt255

Reputation: 3566

You can use takeUntil from RxJS. takeUntil will stop subscription. See the example below.

class myComponent {
  private destroyed$: ReplaySubject<boolean> = new ReplaySubject(1);

  ngOnInit() {
    return Observable.interval(2000).switchMap(() => {
      return super.doRequest('/audit/api/' + this.API_version + '/Query/GetFlowHistory?sagaId=' + sagaId, 'get', {}).map((responseData) => {
        return responseData
      });
    }).takeUntil(this.destroyed$)
  }

  destroy() {
    this.destroyed$.next(true);
    this.destroyed$.complete();
  }
}

Upvotes: 7

Related Questions