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:
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With