The reduce() operator lets you run a function to accumulate all the values of an Observable to generate a new Observable containing only one value (the accumulated value).
This operator has the following signature:
observable.reduce(accumulatorFunction,[initialValue]);
The first parameter is optional and the second one is mandatory:
- accumulatorFunction: This is a function that is used to accumulate values from an observable. This function can receive up to four parameters:
-
- acc: This is an accumulated value
- currentValue: This is the value used in this iteration
- currentIndex: This is a zero-based index of this iteration
- source: This is the observable used
- initialValue: This is the initial accumulator
We can use this function to sum up all the values in an Observable containing numbers, as follows:
Rx.Observable
.of(1,2,3)
.reduce((acc,current)=>acc+current)
.subscribe(...