user3145373 ツ
user3145373 ツ

Reputation: 8146

angular 2 detect if any RxJS timer is running or not

I am working on angular2 application. I have scheduler requirement that runs on period of pre-configured time.

I have mainly 2 component in my application:

1: HomeComponent, 2: MasterComponent.

My master component will always be there in browser, all other component are it's child component of it.

Now I have added RxJS timer in ngOnInit()..

Now when I go to HomeComponent, MasterComponent is out of scope and when I came back to MasterComponnent another times starts(already first is working).. So Now I have 2 timers.

So want to detect if any times is running then not start otherwise start.

I need to start times only when user logs in.

Master Component Code:

ngOnInit() {
    let timer = Observable.timer(2000, 1000);
    timer.subscribe(this.printConsole);
}

printConsole() {
    console.log("ticks: " + new Date());
}

is there anyway so in ngOnInit I can detect any Timer already running or not !

Upvotes: 1

Views: 1261

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71921

Create a static variable on your MasterComponent:

export class MasterComponent {

  public static TIMER;

  ngOnInit() {
      if(!MasterComponent.TIMER) {
         MasterComponent.TIMER = Observable.timer(2000, 1000);    
      }
  }
}

Another option, and this has my personal preference, could be to create a singleton service in your application and let that service create the timer. Then inject this service into your MasterComponent and subscribe to the timer. For example:

export class MasterTimer {

   public get timer() {
       return this._timer;
   }

   private _timer;

   constructor() {}

   public initTimer(): void {
      if(!this._timer) {
         this._timer = Observable.timer(2000, 1000);
      }
   }
}

Your MasterComponent will change to this:

export class MasterComponent {

  private _timerSub: Subscription;

  constructor(private _masterTimer: MasterTimer){}

  ngOnInit() {
      this._masterTimer.initTimer();
      this._timerSub = this._masterTimer.timer.subscribe(this.printConsole);
  }

  ngOnDestroy() {
      this._timerSub.unsubscribe();
  }
}

Upvotes: 1

Related Questions