执行一系列动态创建的可观测对象数组 [英] Execute dynamically created array of observables in series
问题描述
我正在开发一个项目(Angular2),在其中动态创建Observables并将其放置在数组中
I am working on a project (Angular2) where I am creating Observables dynamically and putting them in an array
var ObservableArray : Observable<any>[] = [];
//filling up Observable array dynamically
for (var i = 0; i < this.mainPerson.children.length; i++) {
ObservableArray.push(Observable.fromPromise(this.determineFate(this.mainPerson.children[i])));
}
}
var finalObservable: Observable<any> = Observable.concat(ObservableArray);
finalObservable
.subscribe( data => {
//here I expected to execute determineFate() for all observables inside array
console.log("determine fate resolved data returned [" + data + "]");
}, error => {
console.error("error on Age Year for Characters")
},() => {
//Here I expect this gets executed only when all Observables inside my array finishes
console.log("determine fate resolved data returned COMPLETED");
//DB call
});
determineFate(..): Promise<boolean> {
...
return either true / false if success or error;
}
我想连续执行所有可观察对象(forkJoin
似乎并行运行-因此使用了concat).一旦执行了所有可观察项,便要执行一些与数据库相关的代码.但是似乎我在"Completed"块中的代码并不等待所有Observable的完成.我怎样才能做到这一点?
I want to execute all observables in a series (forkJoin
seems to run in parallel - so used concat). Once all observables are executed, want to execute some DB related code. But it seems my code inside 'Completed' block does not wait for all Observables to finish. How can I achieve this?
预先感谢
推荐答案
使用Observable.concat(ObservableArray)
将使数组变平,并从ObservableArray
逐一发出每个Observable.顺便说一句,使用concat
的静态版本仅对两个或多个参数有意义(请参阅
Using Observable.concat(ObservableArray)
will just flatten the array and emit each Observable from ObservableArray
one by one. Btw, using the static version of concat
makes sense only with two or more parameters (see http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-concat).
相反,您可以迭代Observable的数组,并等待直到使用concatAll()
运算符将它们一一完成.
Instead you can iterate the array of Observables and wait until they complete one by one with the concatAll()
operator.
此示例模拟您的用例:
var observableArray = [];
// filling up Observable array dynamically
for (var i = 0; i < 10; i++) {
observableArray.push(Observable.of('Value ' + i));
}
Observable.from(observableArray)
.concatAll()
.subscribe(console.log, null, () => console.log('completed'));
Observable.from()
分别发出每个Observable,而concatAll()
按照发出它们的顺序订阅它们中的每个.
The Observable.from()
emits each Observable separately and concatAll()
subscribes to each one of them in the order they were emitted.
此演示打印以控制台以下输出:
This demo prints to console the following output:
Value 0
Value 1
Value 2
Value 3
Value 4
Value 5
Value 6
Value 7
Value 8
Value 9
completed
这篇关于执行一系列动态创建的可观测对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!