给定数组中的输入列表,我想运行一个返回可观察对象的同步任务。但我需要这些任务不是并行连续运行。如下所示,所有任务都是同时启动的。
我的第二个问题是如何在最后返回的数组中累积fakeAsyncWork的每次迭代的结果。显然我现在在错误的地方扫描。
这是jsbin:http://jsbin.com/kujilow/15/edit?js,console
const source$ = Rx.Observable.of(1,2,3,4)
const job$ = source$
.do(x=>console.log("emitted from source " + x))
.switchMap(n => fakeAsyncWork(n))
.do(x=>console.log("emitted from switch " + x))
.scan((a,c) => a.concat(c), [])
let fakeAsyncWork = (sec): Rx.Observable<any> => {
return new Rx.Observable(observer => {
console.log("start waiting for " + sec);
setTimeout(() => {
console.log("finish waiting " + sec);
observer.next(sec*10)
}, sec*1000);
});
}
job$.subscribe(x => console.log(x) );
目前的结果:
"emitted from source 1"
"start waiting for 1"
"emitted from source 2"
"start waiting for 2"
"emitted from source 3"
"start waiting for 3"
"emitted from source 4"
"start waiting for 4"
"finish waiting 1"
"finish waiting 2"
"finish waiting 3"
"finish waiting 4"
"emitted from switch 40"
[40]
期望的结果:(每个任务在下一个任务开始之前完成)
"emitted from source 1"
"start waiting for 1"
"finish waiting 1"
"emitted from source 2"
"start waiting for 2"
"finish waiting 2"
"emitted from source 3"
"start waiting for 3"
"finish waiting 3"
"emitted from source 4"
"start waiting for 4"
"finish waiting 4"
"emitted from switch [10,20,30,40]"
[10,20,30,40]
干杯:=)