1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
from typing import Any, Callable, Optional, TypeVar
from reactivex import Observable, abc
from reactivex.typing import Predicate, PredicateIndexed
_T = TypeVar("_T")
def take_while_(
predicate: Predicate[_T], inclusive: bool = False
) -> Callable[[Observable[_T]], Observable[_T]]:
def take_while(source: Observable[_T]) -> Observable[_T]:
"""Returns elements from an observable sequence as long as a
specified condition is true.
Example:
>>> take_while(source)
Args:
source: The source observable to take from.
Returns:
An observable sequence that contains the elements from the
input sequence that occur before the element at which the
test no longer passes.
"""
def subscribe(
observer: abc.ObserverBase[_T],
scheduler: Optional[abc.SchedulerBase] = None,
) -> abc.DisposableBase:
running = True
def on_next(value: _T):
nonlocal running
with source.lock:
if not running:
return
try:
running = predicate(value)
except Exception as exn:
observer.on_error(exn)
return
if running:
observer.on_next(value)
else:
if inclusive:
observer.on_next(value)
observer.on_completed()
return source.subscribe(
on_next, observer.on_error, observer.on_completed, scheduler=scheduler
)
return Observable(subscribe)
return take_while
def take_while_indexed_(
predicate: PredicateIndexed[_T], inclusive: bool = False
) -> Callable[[Observable[_T]], Observable[_T]]:
def take_while_indexed(source: Observable[_T]) -> Observable[_T]:
"""Returns elements from an observable sequence as long as a
specified condition is true. The element's index is used in the
logic of the predicate function.
Example:
>>> take_while(source)
Args:
source: Source observable to take from.
Returns:
An observable sequence that contains the elements from the
input sequence that occur before the element at which the
test no longer passes.
"""
def subscribe(
observer: abc.ObserverBase[_T],
scheduler: Optional[abc.SchedulerBase] = None,
) -> abc.DisposableBase:
running = True
i = 0
def on_next(value: Any) -> None:
nonlocal running, i
with source.lock:
if not running:
return
try:
running = predicate(value, i)
except Exception as exn:
observer.on_error(exn)
return
else:
i += 1
if running:
observer.on_next(value)
else:
if inclusive:
observer.on_next(value)
observer.on_completed()
return source.subscribe(
on_next, observer.on_error, observer.on_completed, scheduler=scheduler
)
return Observable(subscribe)
return take_while_indexed
__all__ = ["take_while_", "take_while_indexed_"]
|