简体   繁体   中英

Optimization timer rxjs Observable

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();
  }

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());

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() });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM