RxJS Sovrascrivi timer / Best practice osservabile

Sep 10 2020

Sto cercando di "reimpostare" un timer quando un servizio emette un nuovo tempo di scadenza. Ce l'ho sovrascrivendo l'osservabile. Non sono sicuro se dovrei "garbage collect" l'osservabile OPPURE se c'è un modo migliore per "resettare" il timer.

Questo codice funziona bene ma non sono sicuro che questa sia la migliore pratica

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

Risposte

2 bryan60 Sep 10 2020 at 00:33

Non è troppo chiaro cosa vuoi, ma sembra che questo sia tutto ciò che vuoi fare:

    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?

    }

gli abbonamenti annidati negli abbonamenti sono una cattiva pratica e portano a codice disordinato. utilizzare gli operatori per combinare i flussi secondo necessità.