我需要管理数组迭代延迟的帮助。
关于我的https://jsfiddle.net/mlefree/vrL813j2/93/,有两个问题:
```
...
const arrayAsObservable = of(null).pipe(
delay(500),
switchMap(_ => getObjectWithArrayInPromise()),
map(val => {
log('array', val);
return (val.myArray);
}),
switchMap(val => from(val))
);
const eachElementAsObservable = arrayAsObservable.pipe(
delay(500), // Not working : we want to wait 500ms more for each value
map(val => {
log('value', val);
return val ;
}),
switchMap(val => getNewValueInPromise(val)),
map(val => {
// Not working : why not all new values ?
log('value after computing (KO)', val);
return (val);
})
);
const summarizeAsObservable = eachElementAsObservable.pipe(
// Not working : we want to sum all new values
map(val => {
log('value before reduce (KO)', val);
return val ;
}),
reduce((a,b) => a + b)
);
summarizeAsObservable.subscribe(msg => {
log('We did a total of (KO)', msg);
});
```
答案 0 :(得分:1)
总体而言,代码有点太复杂,有几行成为代码的根本问题。
您在计算(KO)后仅收到一个值的原因是您使用了switchMap
,它将在源发出后取消订阅内部可观察的值,因此您始终会获得最后一个发出的值。我还将延迟更改为timer
和mapTo
发射的值
const eachElementAsObservable = arrayAsObservable.pipe(
concatMap(value => timer(1500).pipe(mapTo(value))), // Not working : we want to wait 500ms for each value
map(val => {
log('value', val);
return val;
}),
mergeMap(val => from(getNewValueInPromise(val))),
map(val => {
// Not working : why not all new values ?
console.log('value after computing (KO)', val);
return (val);
})
);
这是更新过的小提琴https://jsfiddle.net/fancheung/vrL813j2/109/
该代码无法完全正常运行,因为您会因拒绝承诺而抛出错误,从而导致可观察对象停止发射,因此需要在流中放置catchError