首页 文章

RXJS - SwitchMap或SwitchMapTo用于重置计时器

提问于
浏览
0

所以我是RXJS的新手 . 我要做的是设置一个会话到期计时器,当用户收到模块提示他们的会话即将到期时,如果他们点击继续,则重置计时器 .

我一直在阅读switchMap和switchMapTo,但我发现的例子使用了某种点击事件或鼠标移动事件 . 我的情况是,我不想刷新按钮,因为我正在验证JWT . 成功验证JWT后,我将刷新计时器 .

我有一个用于设置计时器的用户的公共库,如下所示:

private tick: Subscription;
public tokenExpirationTime: Subject<number>;

  setupExpirationTimer():void {
    // Start the timer based on the expiration
    var expirationSeconds = this.expiration * 60;
    this.tick = Observable.timer(0, 1000).map(i => expirationSeconds - i).subscribe(x => {
      // Set the seconds in the user object
      this.tokenExpirationTime.next(x);
      console.log("TIMER: " + x);
    });
  }

在我的代码的其他地方,我订阅了tokenExpirationTime(这就是我知道当前时间在计时器上的内容,所以我知道何时显示我的弹出窗口) .

防爆 .

this.user.tokenExpirationTime.subscribe(x => { ... });

我可能做错了,因为我是新手 . 我希望我的解释清楚,但如果没有,请告诉我 . 感谢您的帮助!

1 回答

  • 0

    更换

    Observable.timer(0, 1000)
      // … all the other stuff …
    

    // Whenever reset$ emits…
    reset$
      // (but we emit once initially to get the timer going)
      .startWith(undefined)
      // … start a new timer
      .switchMap(() => Observable.timer(0, 1000))
      // … all the other stuff …
    

    哪里

    private reset$ = new Subject();
    

    然后你可以添加一个像这样的功能

    public resetTimer() {
      this.reset$.next();
    }
    

相关问题