以下代码在其中包含一个计时器和一个get请求。如果请求返回错误,计时器应停止。您可以在内部订阅(即请求)中停止计时器吗?有潜在的内存泄漏吗?这是个好习惯吗?
let sub = timer(500, 1000).subscribe(() => {
this.http.get<any>(url).subscribe(result => {
//...
}, error => {
//...
sub.unsubscribe(); // can this be done here?
});
});
答案 0 :(得分:2)
由于订阅会触发另一个订阅,因此您拥有的代码使清除/跟踪所有内容变得更加困难。
实际上,您可以使用mergeMap
来获得相同的结果(如果请求的时间超过您的轮询间隔,我建议使用switchMap
或concatMap
),还可以使错误传播到顶部Observable
:
let sub = timer(500, 1000).pipe(
switchMap(_ => this.http.get(url))
).subscribe(result => {
...
}, error => {
// sub is already unsubscribed at this point since there was an error
});
对于内存泄漏,如果let sub
与this.sub
相同,则原始代码应该没问题。
答案 1 :(得分:1)
Can you stop the timer within the inner subscription
是的。
Any potential memory leaks
只需要退订ngOnDestroy
中的内容即可。不能说其余的代码,所以我不会说“是”或“否”。
Is it a good practice
好坏都不是,这里只是代码。我认为您没有其他解决方案,例如可以通过Websocket简化代码的方法,仅此而已。