切换映射和取消时间取消挂起 [英] switchMap and debounceTime cancel pending
本文介绍了切换映射和取消时间取消挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个基于搜索词搜索员工的方法。
this._sub.pipe(
debounceTime(500),
filter(x => !!x),
distinctUntilChanged(),
switchMap(this.getResults.bind(this))
).subscribe((d: IDisplayEmp[]) => {
console.log('RES', d)
this.displayResults = d;
});
this._sub.next('mySearchTerm');
这很有效,如果发出新的API调用,以前的API调用将被取消。然而,问题来了。
活动API调用仅在发出去跳后才会取消。如果活动API调用在去抖动等待期间返回,它仍会触发"我的订阅"。
我理解这是因为取消操作仅发生在Switchmap范围内。
是否可以对此进行重构,以便如果取消弹出正在等待输入停止,它将取消所有挂起的API调用?
可能是一种天真的方法,但我尝试了类似下面的方法,它会发送值,但现在没有有效的取消反弹。
this._sub.pipe(
filter(x => !!x),
distinctUntilChanged(),
switchMap((x) => {
return of(x)
.pipe(
debounceTime(500),
this.getResults.bind(this)
);
})
).subscribe((d: IDisplayEmp[]) => {
console.log('RES', d)
this.displayResults = d;
});
感谢您的帮助。
推荐答案
每当this._sub
发出时,使用takeUntil
取消您的请求。
this._sub.pipe(
debounceTime(500),
filter(x => !!x),
distinctUntilChanged(),
switchMap(searchTerm => this.getResults(searchTerm).pipe(
takeUntil(this._sub)
))
).subscribe((d: IDisplayEmp[]) => {
console.log('RES', d)
this.displayResults = d;
});
这篇关于切换映射和取消时间取消挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文