angular - Rxjs 全局任务定时器
问题描述
我正在尝试在我的应用程序上创建一个全局任务计时器。
我正在寻找解决方案: - 当我单击任务的开始进度时,计时器将计数 60 秒。- 但是当我更改页面(另一个组件)并返回上一个时,计时器仍会计数。
你认为冷计时器观察者是个好主意吗?我有实施它的问题。或者,也许 RxJs 有开箱即用的解决方案?
我的意思是-计时器的最佳想法如何持续存在?
谢谢福特的建议。
解决方案
您可以将计时器 Observable 存储在服务中,确保从服务中订阅它,这样它就不会失去所有订阅者。这些方面的东西:
private timer = interval(1000).pipe(take(60));
private timerStarted = false;
startTimer() {
this.timer.pipe(
tap(() => this.timerStarted = true),
finalize(() => this.timerStarted = false)
).subscribe();
}
getTimer() {
return this.timer;
}
getTimerStarted() {
return this.timerStarted;
}
然后,在您的组件中:
private destroy$ = new Subject<boolean>();
ngOnInit() {
if (this.timerService.getTimerStarted()) {
this.timerService.getTimer().pipe(
takeUntil(this.destroy$),
// handle timer stuff here
).subscribe();
}
}
onStartTimer() {
this.timerService.startTimer();
this.timerService.getTimer().pipe(
takeUntil(this.destroy$),
// handle timer stuff here
).subscribe();
}
ngOnDestroy() {
this.destroy$.next(true);
}
编辑:移动take(60)
到 Observable 本身,而不是startTimer
方法内部的那个。这应该可以防止它在从外部订阅时计数超过 60 秒。
推荐阅读
- html - 通过 CLI 下载完整的网站
- mysql - 如何根据 SQL 中的条件在组中选择一行?
- c - 合成器 - 记录按下的键盘
- jquery - 在 Drupal 7 jquery 库中没有在模块中被调用
- python - 配置 Django 的测试调试以打印更短的路径。
- java - 将 IntelliJ 连接到 weblogic 服务器
- android - ConstraintLayout 中 SolverVariable 上的 NPE
- python - 我的函数有什么问题没有使用 python 解析 JSON 文件的大厅内容
- android - 在不使用 GPS 的情况下获取当前位置的经纬度
- android - 如果直接从 onCreate 调用 Android TextToSpeech 不起作用