为什么switchMap不会取消以前的观察者? [英] Why switchMap does not cancel previous observer?
问题描述
我在组件(控制器)中描述了方法:
I have method described in component (controller):
public requestPassportData(): void {
const th = this;
const data = {
get_scanned_data: true
};
Observable.timer(0, 1000)
.switchMap(() => this.requestMethods.requestPassportData(data))
.takeWhile(() => {
return (
th.formRegister.currentForm().index == 1 ||
th.formRegister.currentForm().index == 2 ||
th.formRegister.currentForm().index == 3
);
})
.subscribe(response => {});
}
如果要调用方法requestPassportData()
五次,它将每秒钟发送五个请求到服务器.为什么switchMap不会取消最后一个观察者?
If to call method requestPassportData()
five times, it will send each second five request to server. Why switchMap does not cancel last observer?
推荐答案
由于每次调用requestPassportData()
时,都会使用新的Observable.timer
创建一个与先前的调用无关的新链.
Because every time you call requestPassportData()
you'll create a new chain with new Observable.timer
that has nothing to do with the previous calls.
显然有多种方法可以解决此问题,但是您可以例如执行以下操作:
There are obviously multiple ways to solve this but you can for example do the following:
private requestPasswordSubject$ = new Subject();
private requestPassword = this.requestPasswordSubject$
.switchMap(() => Observable.timer(0, 1000)
.switchMap(() => this.requestMethods.requestPassportData(data))
.takeWhile(() => {
return (
th.formRegister.currentForm().index == 1 ||
th.formRegister.currentForm().index == 2 ||
th.formRegister.currentForm().index == 3
);
});
)
.subscribe(response => {});
public requestPassportData(): void {
...
this.requestPasswordSubject$.next();
}
实际实施取决于您要实现的目标,但希望您能明白与现在的情况有所不同.
Actual implementation depends on what exactly you're trying to achieve but hopefully you get the point what is different to what you have now.
这篇关于为什么switchMap不会取消以前的观察者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!