def _reduce(accumulator: Accumulator, seed: Any = NotSet) -> Callable[[Observable], Observable]: """Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. For aggregation behavior with incremental intermediate results, see `scan()`. Examples: >>> res = reduce(lambda acc, x: acc + x) >>> res = reduce(lambda acc, x: acc + x, 0) Args: accumulator: An accumulator function to be invoked on each element. seed: Optional initial accumulator value. Returns: An operator function that takes an observable source and returns an observable sequence containing a single element with the final accumulator value. """ if seed is not NotSet: scanner = ops.scan(accumulator, seed=seed) return pipe(scanner, ops.last_or_default(default_value=seed)) return pipe(ops.scan(accumulator), ops.last())
def create(): def predicate(x): if x < 4: return x % 2 == 1 else: raise Exception(ex) return xs.pipe(_.last_or_default(predicate, 0))
def _scan(source): if isinstance(source, rs.MuxObservable): return scan_mux(accumulator, seed, reduce)(source) else: _seed = seed() if callable(seed) else seed if reduce is False: return rx.pipe( ops.scan(accumulator, _seed), ops.default_if_empty(default_value=_seed), )(source) else: return rx.pipe( ops.scan(accumulator, _seed), ops.last_or_default(default_value=_seed), )(source)
def last_or_default(source: Observable) -> Observable: """Return last or default element. Examples: >>> res = _last_or_default(source) Args: source: Observable sequence to get the last item from. Returns: Observable sequence containing the last element in the observable sequence. """ if predicate: return source.pipe( ops.filter(predicate), ops.last_or_default(None, default_value), ) return last_or_default_async(source, True, default_value)
def create(): def predicate(x): return x % 2 == 1 return xs.pipe(_.last_or_default(predicate, 0))
def create(): return xs.pipe(_.last_or_default(None, 0))