以rxjs间隔重新启动计时器 [英] Restart the timer on an rxjs interval

查看:205
本文介绍了以rxjs间隔重新启动计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类,该类设置了一个可间隔观察到的可暂停的rxjs:

I created a class which sets up a pausable rxjs observable on an interval:

export class RepeatingServiceCall<T> {
  private paused = false;
  private observable: Observable<T>;
  constructor(serviceCall: () => Observable<T>, delay: number) {
    this.observable = interval(delay).pipe(flatMap(() => (!this.paused ? serviceCall() : NEVER)));
  }
  setPaused(paused: boolean) {
    this.paused = paused;
  }
  getObservable() {
    return observable;
  }
}

这似乎工作正常,但是我要解决的问题是我希望计时器在不暂停时重置.因此,假设间隔时间是上次发出间隔setPaused(false)的时间之后的10秒和5秒.在这种情况下,我希望它立即发出,然后重新启动计时器.这样添加起来会很容易吗?

This seems to work fine but the problem I am trying to solve is that I want the timer to reset when unpaused. So let's say that the interval time is 10 seconds and 5 seconds after the last time the interval emitted, setPaused(false) is called. In that scenario, I want it to emit immediately and then restart the timer. Would something like that be an easy thing to add?

推荐答案

如果使用timer而不是interval,并将初始延迟设置为0,则间隔将立即触发.

If you use timer instead of interval, and set the initial delay to 0, then your interval will fire immediately.

您可以使用takeUntil运算符来防止间隔始终运行,而repeatWhen运算符可以在需要时重新启动它:

You can use takeUntil operator to prevent the interval to run always, and repeatWhen operator to restart it whenever you want:

import { Observable, Subject, timer } from 'rxjs';
import { repeatWhen, switchMap, takeUntil } from 'rxjs/operators';

export class RepeatingServiceCall<T> {
  readonly observable$: Observable<T>;
  private readonly _stop = new Subject<void>();
  private readonly _start = new Subject<void>();

  constructor(serviceCall: () => Observable<T>, delay: number) {
    this.observable$ = timer(0, delay)
      .pipe(
        switchMap(() => serviceCall()),
        takeUntil(this._stop),
        repeatWhen(() => this._start)
      );
  }
  start(): void {
    this._start.next();
  }
  stop(): void {
    this._stop.next();
  }
}

这是一个有效的 StackBlitz示例.

P.S.:getter和setter在打字稿中的工作方式不同.因此,您不需要经典的吸气剂概念,只需将属性设置为publicreadonly.

P.S.: Getters and setters are working different in typescript. So you do not need classic getter concept, you can just make the attribute public and readonly.

这篇关于以rxjs间隔重新启动计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆