以下代码中包含一个计时器和一个get请求。如果请求返回错误,计时器应停止。您可以在内部订阅(即请求)中停止计时器吗?有潜在的内存泄漏吗?这是一个好习惯吗?
let sub = timer(500, 1000).subscribe(() => {
this.http.get<any>(url).subscribe(result => {
//...
}, error => {
//...
sub.unsubscribe(); // can this be done here?
});
});
由于订阅触发另一个,因此您拥有的代码使清除/跟踪所有内容变得更加困难。
您实际上可以使用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
相同,则原始代码应该没问题。
Can you stop the timer within the inner subscription