Reduce

Definition

class broqer.op.Reduce(function: Callable[[Any, Any], Any], init: Any)[source]

Apply function to the current emitted value and the last result of function.

Parameters:
  • function – function taking the emitted value and the last result of the last run.
  • init – initialisation used as “first result” for the first call of function on first emit.

Usage

Apply function to the current emitted value and the last result of function.

Usage:

>>> from broqer import Subject, op
>>> s = Subject()
>>> def build_number(last_result, value):
...     return last_result*10+value
>>> reduce_publisher = s | op.Reduce(build_number, 0)
>>> _d = reduce_publisher | op.Sink(print, 'Reduce:')
>>> s.emit(4)
Reduce: 4
>>> s.emit(7)
Reduce: 47
>>> s.emit(8)
Reduce: 478
>>> s.emit(1)
Reduce: 4781

Reseting (or just setting) the state is also possible:

>>> reduce_publisher.reset(123)
>>> s.emit(4)
Reduce: 1234