Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS reduce doesn't continue

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:

Error screenshot

like image 237
Henrik Avatar asked Nov 08 '15 16:11

Henrik


People also ask

What is reduce in RxJS?

The RxJS reduce() operator is a mathematical operator that applies an accumulator function over the input or source Observable, which returns an accumulated value in an observable form when the source is completed. It also gives an optional seed value.

What is scan in RxJS?

Updated 4 years ago. The scan operator in RxJS is the main key to managing values and states in your stream. Scan behaves just as a reduce function would, but scan is able to collect values from streams over time.

What is stream in RxJS?

An observable represents a stream, or source of data that can arrive over time. You can create an observable from nearly anything, but the most common use case in RxJS is from events. This can be anything from mouse moves, button clicks, input into a text field, or even route changes.

What is reactive programming in js?

Reactive Programming in JavaScript is like a sequence of events that occur in time. It is an Asynchronous Programming concept around data streams. Reactive programming is a programming paradigm for writing code, mainly concerned with asynchronous data streams. It is a programming of event streams that happens in time.


1 Answers

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.

like image 99
Ryan Kennedy Avatar answered Nov 14 '22 12:11

Ryan Kennedy