I have two timer that runs in my app. The timer2 should start at 10secs when I clicked the button but my timer2 only continues my timer1.

I have tried unsubscribing but it doesnt seem to work. Any help would be much appreciated.

app.component.ts

import { Component } from '@angular/core';
import { timer } from 'rxjs';
import { filter, takeWhile } from 'rxjs/operators';
import { CountdownService } from './countdown.service'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  value1: string | number;

  value2: string | number;

  constructor( private countdownService: CountdownService) {
  // countdown is started
    countdownService.start(10);

    // first subscriber subscribes
    countdownService.countdown().subscribe(
      t => {
        this.value1 = t
      },
      null, 
      () => this.value1 = 'Done!'
    );
  }

  newTimer() {
    this.countdownService.start(10);
    this.countdownService.countdown().subscribe(
       t => this.value2 = t, 
        null, 
        () => this.value2 = 'Done!'
      );

  }
}

service

import { Injectable } from '@angular/core';
import { timer, Subject, Observable } from 'rxjs';
import { takeWhile, map } from 'rxjs/operators';

@Injectable()
export class CountdownService {

  private _countdown = new Subject<number>();

  countdown(): Observable<number> {
    return this._countdown.asObservable();
  }

  private isCounting = false;

  start(count: number): void {
    // Ensure that only one timer is in progress at any given time.
    if (!this.isCounting) {
      this.isCounting = true;
      timer(0, 1000).pipe(
        takeWhile(t => t < count),
        map(t => count - t)
      ).subscribe(
        t => this._countdown.next(t),
        null,
        () => {
          this._countdown.complete();
          this.isCounting = false;
          // Reset the countdown Subject so that a 
          // countdown can be performed more than once.
          this._countdown = new Subject<number>();
        }
      );
    }
  }
}

html

<h1>{{ value1 }}</h1>
<h1>{{ value2 }}</h1>


 <div>
    <button (click)="newTimer()" class="btn btn-link btn-sm">New</button>
  </div>

when my timer2 starts, timer1 should stop and timer 2 should start at 10 secs Here's what I've found and modified it but no luck..

https://stackblitz.com/edit/angular-sexrqx?file=src%2Fapp%2Fapp.component.html

0 Answers