1

I am trying to "reset" a timer when a service emits a new Expiration time. I have it overwriting the observable. I am not sure if i should "garbage collect" the observable OR if there is a better way to "reset" the timer.

This code works fine but i am unsure if this is best practices

    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);
      });
    }
Ricardo Saracino
  • 1,345
  • 2
  • 16
  • 37
  • 1
    you need to explain better what you're trying to accomplish here as the goal is very unclear from what you've got here. – bryan60 Sep 09 '20 at 17:26

1 Answers1

2

Not overly clear what you want, but it seems like this is all you want to do:

    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?

    }

subscriptions nested inside subscriptions are a bad practice and lead to messy code. use operators to combine streams as needed.

bryan60
  • 28,215
  • 4
  • 48
  • 65
  • i added the openModal code to my example, it was done to reduce code duplication.Your code works perfectly and i was certain there was a better way to do this with a switchMap. Thanks for the quick reply – Ricardo Saracino Sep 09 '20 at 18:10