【问题标题】:RxJS Overwrite Timer/Observable Best PracticeRxJS Overwrite Timer/Observable 最佳实践
【发布时间】:2020-12-28 04:12:27
【问题描述】:

我正在尝试在服务发出新的过期时间时“重置”计时器。我让它覆盖了可观察的。我不确定我是否应该“垃圾收集”可观察对象,或者是否有更好的方法来“重置”计时器。

此代码运行良好,但我不确定这是否是最佳做法

    const openModal = () => {
      if (this.sessionModal === null) {
        this.sessionModal = this.modalService.open(SessionModalComponent, {size: 'sm', backdrop: 'static', keyboard: false});
        this.sessionModal.result.then(() => this.sessionModal = null);
      }
    };

    this.expiresAt = authService.expiresAt;

    if (this.expiresAt !== null) {

      this.sessionTimerSubscription
        = timer(this.expiresAt.getTime() - (new Date()).getTime() - this.sessionModalOffset).subscribe(openModal);

      authService.expiresAt$.subscribe((expiresAt) => {

        this.expiresAt = expiresAt;

        this.sessionTimerSubscription.unsubscribe();
        this.sessionTimerSubscription
          = timer(this.expiresAt.getTime() - (new Date()).getTime() - this.sessionModalOffset).subscribe(openModal);
      });
    }

【问题讨论】:

  • 您需要更好地解释您要在这里完成的工作,因为目标与您在这里的内容非常不清楚。

标签: angular typescript rxjs rxjs-observables


【解决方案1】:

不太清楚你想要什么,但似乎这就是你想做的一切:

    this.expiresAt = authService.expiresAt;

    if (this.expiresAt !== null) {

      // when the signal emits
      authService.expiresAt$.pipe(
        startWith(this.expiresAt), // starting with the current value
        tap(expiresAt => this.expiresAt = expiresAt), // set the state (if you must?)
        switchMap(expiresAt =>  // switch into a new timer
          timer(expiresAt.getTime() - (new Date()).getTime() - this.sessionModalOffset)
        )
      ).subscribe(openModal); // subscribe the modal?

    }

订阅嵌套在订阅中是一种不好的做法,会导致代码混乱。根据需要使用运算符组合流。

【讨论】:

  • 我将 openModal 代码添加到我的示例中,这样做是为了减少代码重复。您的代码完美运行,我确信有更好的方法可以使用 switchMap 来做到这一点。感谢您的快速回复
猜你喜欢
  • 2013-12-29
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
  • 2014-12-21
  • 2010-12-23
  • 2010-10-14
相关资源
最近更新 更多