| Conditions | 2 |
| Total Lines | 32 |
| Code Lines | 15 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
| 1 | from typing import Any |
||
| 10 | def rx_avg(observable: Observable) -> Observable: |
||
| 11 | """Create an observable wich return the average items in the source when completes. |
||
| 12 | |||
| 13 | Args: |
||
| 14 | observable (observable): the observable source |
||
| 15 | |||
| 16 | Returns: |
||
| 17 | (Observable): observable instance |
||
| 18 | |||
| 19 | """ |
||
| 20 | |||
| 21 | _count = 0 |
||
| 22 | |||
| 23 | async def accumulator(current, item): |
||
| 24 | nonlocal _count |
||
|
|
|||
| 25 | _count += 1 |
||
| 26 | return current + item |
||
| 27 | |||
| 28 | async def _subscribe(an_observer: Observer) -> Subscription: |
||
| 29 | |||
| 30 | reducer = rx_reduce(observable=observable, accumulator=accumulator, seed=0) |
||
| 31 | |||
| 32 | async def _on_next(item: Any): |
||
| 33 | nonlocal _count |
||
| 34 | if _count == 0: |
||
| 35 | await an_observer.on_error('No value emitted') |
||
| 36 | else: |
||
| 37 | await an_observer.on_next(item / _count) |
||
| 38 | |||
| 39 | return await reducer.subscribe(an_observer=rx_observer_from(observer=an_observer, on_next=_on_next)) |
||
| 40 | |||
| 41 | return rx_create(subscribe=_subscribe) |
||
| 42 |