Home > Enterprise >  Optimization timer rxjs Observable
Optimization timer rxjs Observable

Time:03-17

I have a function to start the timer using rxjs, how can I optimize my logic

 public startTimer(): void {
    this.timeLeft$ = timer(0, 1000)
      .pipe(
        take(this.minutes * 60   1),
        map(() => this.seconds - 1),
        tap(() => this.seconds--),
        takeWhile(seconds => seconds >= 0),
        shareReplay(1),
      );

    this.timeLeft$
      .pipe(
        takeUntil(this.ngUnsubscribe$),
        filter(() => this.seconds === 0),
        tap(() => this.openModal())
      )
      .subscribe();
  }

CodePudding user response:

Well, what exactly you want to optimize :)?

Personally, I'd do it like this:

this.timeLeft$ = timer(0, 1000)
  .pipe(
    take(this.minutes * 60   1),
    map(counter => this.seconds - (1   counter)),
    takeWhile(seconds => seconds >= 0),
    shareReplay(1),
  );

this.timeLeft$
  .pipe(
    filter(() => this.seconds === 0),
    takeUntil(this.ngUnsubscribe$),
  )
  .subscribe(() => this.openModal());

CodePudding user response:

Usually for this kind of operation you want to use the "scan" operator and work with the seconds passed. (Remember that "timer" operator emits the number of seconds that have passed since the start of the first subscription).

In the second observable you don't need any operator, when the timeLeft$ completes you can do your operations.

const timeLeft$ = timer(0, 1000).pipe(
  scan((acc) => --acc, seconds),
  takeWhile((secondsPassed) => secondsPassed >= 0),
  shareReplay(1)
);

timeLeft$.subscribe({ complete: () => this.openModal() });
  • Related