【发布时间】:2018-03-15 14:30:06
【问题描述】:
switchMap的以下用法...
Rx.Observable.timer(0, 1000)
// First switchMap
.switchMap(i => {
if (i % 2 === 0) {
console.log(i, 'is even, continue');
return Rx.Observable.of(i);
}
console.log(i, 'is odd, cancel');
return Rx.Observable.empty();
})
// Second switchMap
.switchMap(i => Rx.Observable.timer(0, 500).mapTo(i))
.subscribe(i => console.log(i));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.min.js"></script>
... 产生以下输出:
0 is even, continue
0
0
1 is odd, cancel
0 // <-------------------- why?
0 // <-------------------- why?
2 is even, continue
2
2
3 is odd, cancel
2 // <-------------------- why?
2 // <-------------------- why?
4 is even, continue
.
.
.
我希望得到以下输出:
0 is even, continue
0
0
1 is odd, cancel
2 is even, continue
2
2
3 is odd, cancel
4 is even, continue
.
.
.
我预计第一个 switchMap 会在每次返回时取消下游的所有内容,我猜这是不正确的。
有没有办法实现期望的行为?
【问题讨论】:
-
提示:让你的代码可以运行,这样其他人就能更容易地尝试解决你的问题
-
@JuanMendes 谢谢,不知道它适用于控制台输出!
标签: javascript rxjs switchmap