RxJS Overwrite Timer / Observable Best Practice
Sep 10 2020
Próbuję „zresetować” licznik czasu, gdy usługa emituje nowy czas wygaśnięcia. Mam to nadpisując to, co obserwowalne. Nie jestem pewien, czy powinienem „zbierać śmieci” obserwowalne, LUB czy istnieje lepszy sposób na „zresetowanie” timera.
Ten kod działa dobrze, ale nie jestem pewien, czy to najlepsze praktyki
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);
});
}
Odpowiedzi
2 bryan60 Sep 10 2020 at 00:33
Nie jest do końca jasne, czego chcesz, ale wygląda na to, że to wszystko, co chcesz zrobić:
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?
}
subskrypcje zagnieżdżone w subskrypcjach są złą praktyką i prowadzą do niechlujnego kodu. użyj operatorów do łączenia strumieni w razie potrzeby.