Home > OS >  How to use defer in rxjs timer?
How to use defer in rxjs timer?

Time:12-14

I am implementing a countdown timer with goes 5:00, 4:59,4:58...so on. How should I just use the input value as it is and not have a default assigned? I have an environment variable which configures duration value.

How to use a setter or ngOnChanges to only start the timer once the value is set?

Will the takeWhile run for seconds 1 ?

export class CountdownComponent {
  @Input() duration = 300
  timeRemaining$ = timer(0, 1000).pipe(
    map(n => (this.seconds - n) * 1000),
    takeWhile(n => n >= 0),
  )
}

I tried this.

export class CountdownComponent {
  @Input() duration = 300
  timeRemaining$ = defer(of(this.seconds)).pipe(switchMap(seconds => timer(0, 1000).pipe(map(n => seconds - n)),
    takeWhile(n => n >= 0),
  )
}

CodePudding user response:

I have been doing timers like this:

const duration = 60;

timer$
  .range(0, duration   1)
  .map(i => duration - i)
  .subscribe(i => console.log(i));

Then use seconds to minutes function

CodePudding user response:

You can use a setter to feed @Input() changes into a ReplaySubject, then define your timeRemaining$ to start from the subject:

export class CountDownComponent {

  private duration$ = new ReplaySubject<number>(1);

  @Input() set duration(value: number) {
    this.duration$.next(value);
  }

  timeRemaining$ = this.duration$.pipe(
    switchMap(duration => timer(0, 1000).pipe(
      map(n => (duration - n) * 1000),
      takeWhile(n => n >= 0),
    ))
  );

}

Here's a working StackBlitz demo.

  • Related