[英]Wait until an unknown number of observables complete
有很多类似性质的问题,我认为这有点不同。
考虑以下代码:
arr = [];
this.service1.getItem()
.subscribe(item => {
Object.entries(item).forEach(([key, value]) => {
if (some_condition_true) {
this.service2.getSomeItems2(value.prop1).pipe(first())
.subscribe(result => value.xyz = result);
this.arr.push(value);
}
});
});
// This line should execute only after the 'forEach' above completes
this.someService.someMethod(arr);
问题是我不知道预先调用service2.getSomeItems2
多少次。
另外, zip
和forkJoin
采用Observables
但我已经订阅了。 也许我可以tap
而不是subscribe
。 但是事实仍然是未知数的Observable。
这个怎么样?
this.service1.getItem()
.pipe(switchMap(items => {
const itemReqs = Object.entries(items)
.filter(v => some_condition_true_or_false)
.map(item => this.service2.getSomeItems2(item.prop1).pipe(first()));
return forkJoin(itemReqs);
}))
.subscribe(data_from_service_2_calls => {
data_from_service_2_calls.forEach(v => console.log(v))
});
可能存在语法错误,但我认为这是您想要的。 请记住,您应该避免在内部订阅。
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.