RxJS覆盖计时器/可观察的最佳实践

问题描述

当服务发出新的到期时间时,我试图“重置”计时器。我覆盖了可观察的东西。我不确定是否应该“垃圾收集”可观察到的东西,或者是否有更好的方法“重置”计时器。

代码可以正常工作,但我不确定这是否是最佳做法

    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);
      });
    }

解决方法

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

    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?

    }
嵌套在订阅中的

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