Code Duplication    Length = 37-38 lines in 2 locations

async_rx/observable/rx_distinct.py 1 location

@@ 10-47 (lines=38) @@
7
__all__ = ["rx_distinct"]
8
9
10
def rx_distinct(observable: Observable, frame_size: int) -> Observable:
11
    """Create an observable which send distinct event inside a windows of size #frame_size.
12
13
    Args:
14
        observable (Observable): observable source
15
        frame_size (int): windows size
16
17
    Returns:
18
        (Observable): observable instance
19
20
    Raise:
21
        (RuntimeError): if frame_size <= 0
22
23
    """
24
    if frame_size <= 0:
25
        raise RuntimeError('framesize must be greather than zero')
26
27
    async def _subscribe(an_observer: Observer) -> Subscription:
28
29
        # our frame buffer
30
        _q: Deque = deque(maxlen=frame_size)
31
32
        async def _on_next(item: Any):
33
            nonlocal _q
34
35
            if item not in _q:  # distinct value
36
                _q.append(item)
37
                await an_observer.on_next(item)
38
39
        async def _on_completed():
40
            nonlocal _q
41
42
            _q.clear()
43
            await an_observer.on_completed()
44
45
        return await observable.subscribe(an_observer=rx_observer_from(observer=an_observer, on_next=_on_next, on_completed=_on_completed))
46
47
    return rx_create(subscribe=_subscribe)
48

async_rx/observable/rx_last.py 1 location

@@ 10-46 (lines=37) @@
7
__all__ = ["rx_last"]
8
9
10
def rx_last(observable: Observable, count: int = 1) -> Observable:
11
    """Create an observale which only take #count (or less) last events and complete.
12
13
    Args:
14
        observable (Observable): observable source
15
        count (int): number of event to get (default 1)
16
17
    Returns:
18
        (Observable): observable instance
19
20
    Raise:
21
        (RuntimeError): if count <= 0
22
23
    """
24
    if count <= 0:
25
        raise RuntimeError('count must be greather than zero')
26
27
    async def _subscribe(an_observer: Observer) -> Subscription:
28
        # local buffer of #count
29
        _q: Deque = deque(maxlen=count)
30
31
        async def _on_next(item: Any):
32
            nonlocal _q
33
34
            _q.append(item)
35
36
        async def _on_completed():
37
            nonlocal _q
38
39
            for item in _q:
40
                await an_observer.on_next(item)
41
            _q.clear()
42
            await an_observer.on_completed()
43
44
        return await observable.subscribe(an_observer=rx_observer_from(observer=an_observer, on_next=_on_next, on_completed=_on_completed))
45
46
    return rx_create(subscribe=_subscribe)
47