Home > Mobile >  Unsubscribe to timer not possible if component destroyed quickly
Unsubscribe to timer not possible if component destroyed quickly

Time:11-23

I have a component that make a loop api calls using rxjs timer operator

My problem is that if the component get destroyed ( for example close the modal ) within 5 seconds I get a loop calls seconds after ( May be the timer get not unsubscribed because it does not return yet a subscription )

What I would like to do is that timer does not make loop calls if I destroy component within 5 seconds.

import {Component, OnInit, OnDestroy} from '@angular/core';
import { Observable, Subscription, timer } from 'rxjs/Rx';

@Component({
    templateUrl: 'app/pages/CurrentRuns/currentruns.component.html'
})
export class CurrentRunsComponent implements OnInit, OnDestroy {

    // Subscription object
    private sub: Subscription;

    ngOnInit() {
        this.sub= timer(firstcheckVal, 2500)
          .pipe(switchMap(() => this.testService.getTestdata())).subscribe(data => {
             ...
          }

    ngOnDestroy(){
        console.log("Destroy timer");
        // unsubscribe here
        if (this.sub) {
          this.sub.unsubscribe();
        }
    }
}

CodePudding user response:

First declare the timer subscription like this:

private timer: Subscription;

And then, in ngOnDestroy you need to unsubscribe to timer subscription:

 this.timer.unsubscribe();

For reference, check this stackblitz, the timer will emit the first value after2.5 sec and then subsequently after 5 secs, but I am unsubscribing after 1 sec so there won;t be any value emitted by timer.

So at least one emission of timer will depend on the value of firstcheckVal. Check the timer API

CodePudding user response:

As a standard practice, within your component, add

private destroy$ = new Subject();

ngOnDestroy(): void {
    if (this.destroy$) {
        this.destroy$.next();
        this.destroy$.complete();
    }
}

Then you don't have to worry about references to subscriptions or unsubscribing because at the end of your pipe you can add takeUntil(this.destroy$)

If you have another observable, same thing. They can all takeUntil(this.destroy$) and they'll automatically be closed and completed without having to make sure you unsubscribe.

  • Related