简体   繁体   English

优化定时器 rxjs Observable

[英]Optimization timer rxjs Observable

I have a function to start the timer using rxjs, how can I optimize my logic我有一个 function 使用 rxjs 启动定时器,我该如何优化我的逻辑

 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.在第二个可观察对象中,您不需要任何运算符,当 timeLeft$ 完成时,您可以进行操作。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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