RxJS reduce doesn't continue

三世轮回 提交于 2019-12-08 20:23:14

问题


Why doesn't the flatMap cause downstream reductions to fire?

I got code like:

handleFiles.flatMap(files =>
  Rx.Observable.from(files).
  flatMap((file, i) => fileReader(file, i)).
  reduce((form, file, i) => {
    form.append('file[' + i + ']', result);
    console.log('reduce step', file);
    return form;
  }, new FormData()).
  tap(console.log.bind(console, 'after reduce'))
).
subscribe(console.log.bind(console, 'response'));

And the problem is that the 'after reduce' tap is never hit. Why?

The log is like:

reduce step [data]
reduce step [data]

Screenshot:


回答1:


The problem isn't in flatMap; it's in the way reduce works.

reduce reads in a whole stream and reduces it to a single value, emitted only when the source stream is closed. If your from(files) stream doesn't end, then reduce will never output its value.

Try using scan instead; it emits each intermediate step and seems to be what you're looking for.




回答2:


If files is an array, then reduce should terminate if the observable returned from fileReader does. So for this code, the problem was that fileReader returned an observable that didn't complete.



来源:https://stackoverflow.com/questions/33595954/rxjs-reduce-doesnt-continue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!