The reduce operator performs some computations over all the items of the source observable and emits a single item that contains the result of this computation. The following figure shows the marble diagram of this operator:
Its prototype is the following:
Observable.reduce(self, accumulator, seed=None)
The accumulator parameter is a function that implements a computation on each item. This function takes two parameters: the accumulated (acc) value and the item (i). Its prototype is this one:
def accumulator(acc, i)
This function must return the new accumulated value.
The seed parameter allows us to set the initial value of accumulator. In cases where the source observable emits no items, then this value is also the one emitted by the reduce operator.
Here is an example of the reduce operator:
numbers = Observable.from_([1, 2, 3, 4])
numbers1.reduce(lambda acc, i: acc + i, seed=0).subscribe(
on_next = lambda i: print("on_next {}".format(i)),
on_error = lambda e: print("on_error: {}".format(e)),
on_completed = lambda: print("on_completed")
)
The example gives the following result: