[英]RxJS Overwrite Timer/Observable Best Practice
當服務發出新的到期時間時,我試圖“重置”計時器。 我讓它覆蓋了可觀察的。 我不確定我是否應該“垃圾收集”可觀察對象,或者是否有更好的方法來“重置”計時器。
這段代碼工作正常,但我不確定這是否是最佳實踐
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?
}
嵌套在訂閱中的訂閱是一種不好的做法,會導致代碼混亂。 使用運算符根據需要組合流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.