[英]RxJS Overwrite Timer/Observable Best Practice
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);
});
}
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.
使用运算符根据需要组合流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.