繁体   English   中英

重置Observable.timer()

[英]Reset Observable.timer()

我已经尝试制作计时器,但是有一个问题,我无法理解如何重置(刷新)计时器。

startTimer() {
Observable.timer(this.countDownDuration, 1000)
        .map(i => this.countDownDuration - i)
        .take(this.countDownDuration + 1)
        .subscribe(i => {
          this.countDown = i;
          console.log(this.countDown);
        });
}

resetTimer() {
  must stop previous timer and start new 
}

有什么建议么

const s = new BehaviorSubject(null);

s.switchMap(() => Observable.timer(this.countDownDuration, 1000))
  .map(...)
  ...
  .subscribe(...);

resetTimer() {
  s.next();
}

我找到了另一种方法。 在我的示例中,我必须使用take。 我知道如何重置throwSwitchMap。 但这对我不好。 可能这不是一个好决定。

status;

startTimer() {
this.status = Observable.timer(this.countDownDuration, 1000)
        .map(i => this.countDownDuration - i)
        .take(this.countDownDuration + 1)
        .subscribe(i => {
          this.countDown = i;
          console.log(this.countDown);
        });
}

resetTimer() {
  this.status.unsubscribe(); 
  this.startTimer();
}

马丁的答案( https://stackoverflow.com/a/51726532/3024975 )是正确的,但我不喜欢订阅BehaviorSubject。 因此,这是一种替代方法:

我们需要一种方法来初始化可观察对象以重新启动自身。 这是Subject好用例

const signal = new Subject();

Observable.defer(() => Observable.timer(this.countDownDuration, 1000))
  .takeUntil(signal)
  .repeat()
  .map(....)
  .subscribe(...);

resetTimer() {
  signal.next();
}

我使用takeUntil停止Observable并立即使用repeat重复它。 defer用于创建具有新this.countDownDuration值的计时器(我希望它会改变)。

这是另一个解决方案:

  recording$ = new BehaviorSubject(false);
  stopWatch$: Observable<number>;

  ngOnInit() {

    this.stopWatch$ = this.recording$.pipe(
      switchMap(r => r ? timer(0, 10) : never()),
      share()
    );

  }

  start() {
    this.recording$.next(true);
  }

  stop() {
    this.recording$.next(false);
  }

暂无
暂无

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

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