def partition(source: Observable[_T]) -> List[Observable[_T]]: """The partially applied `partition` operator. Returns two observables which partition the observations of the source by the given function. The first will trigger observations for those values for which the predicate returns true. The second will trigger observations for those values where the predicate returns false. The predicate is executed once for each subscribed observer. Both also propagate all error observations arising from the source and each completes when the source completes. Args: source: Source obserable to partition. Returns: A list of observables. The first triggers when the predicate returns True, and the second triggers when the predicate returns False. """ def not_predicate(x: _T) -> bool: return not predicate(x) published = source.pipe( ops.publish(), ops.ref_count(), ) return [ published.pipe(ops.filter(predicate)), published.pipe(ops.filter(not_predicate)), ]
def create(): def mapper(xy): x, y = xy return "{}{}".format(x.value, y.value) return xs.pipe( ops.join( ys, lambda x: reactivex.timer(x.interval).pipe( ops.filter(lambda _: False)), lambda y: reactivex.timer(y.interval).pipe( ops.filter(lambda _: False)), ), ops.map(mapper), )
def first_( predicate: Optional[Predicate[_T]] = None, ) -> Callable[[Observable[_T]], Observable[_T]]: """Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. Examples: >>> res = res = first()(source) >>> res = res = first(lambda x: x > 3)(source) Args: predicate -- [Optional] A predicate function to evaluate for elements in the source sequence. Returns: A function that takes an observable source and returns an observable sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. """ if predicate: return compose(ops.filter(predicate), ops.first()) return first_or_default_async_(False)
def single_or_default_( predicate: Optional[Predicate[_T]] = None, default_value: _T = None ) -> Callable[[Observable[_T]], Observable[_T]]: """Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists this method reports an exception if there is more than one element in the observable sequence. Examples: >>> res = single_or_default() >>> res = single_or_default(lambda x: x == 42) >>> res = single_or_default(lambda x: x == 42, 0) >>> res = single_or_default(None, 0) Args: predicate -- [Optional] A predicate function to evaluate for elements in the source sequence. default_value -- [Optional] The default value if the index is outside the bounds of the source sequence. Returns: An observable Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. """ if predicate: return compose( ops.filter(predicate), ops.single_or_default(None, default_value) ) else: return single_or_default_async_(True, default_value)
def last(source: Observable[_T]) -> Observable[Any]: """Partially applied last operator. Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. Examples: >>> res = last(source) Args: source: Source observable to get last item from. Returns: An observable sequence containing the last element in the observable sequence that satisfies the condition in the predicate. """ if predicate: return source.pipe( operators.filter(predicate), operators.last(), ) return last_or_default_async(source, False)
def open(self): scheduler = AsyncIOScheduler(asyncio.get_event_loop()) print("WebSocket opened") # A Subject is both an observable and observer, so we can both subscribe # to it and also feed (send) it with new values self.subject: Subject[Dict[str, str]] = Subject() # Get all distinct key up events from the input and only fire if long enough and distinct searcher = self.subject.pipe( ops.map(lambda x: x["term"]), ops.filter(lambda text: len(text) > 2 ), # Only if the text is longer than 2 characters ops.debounce(0.750), # Pause for 750ms ops.distinct_until_changed(), # Only if the value has changed ops.flat_map_latest(search_wikipedia), ) def send_response(x: HTTPResponse) -> None: self.write_message(x.body) def on_error(ex: Exception): print(ex) searcher.subscribe(on_next=send_response, on_error=on_error, scheduler=scheduler)
def first_or_default_( predicate: Optional[Predicate[_T]] = None, default_value: Optional[_T] = None ) -> Callable[[Observable[_T]], Observable[_T]]: """Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. Examples: >>> res = source.first_or_default() >>> res = source.first_or_default(lambda x: x > 3) >>> res = source.first_or_default(lambda x: x > 3, 0) >>> res = source.first_or_default(None, 0) Args: source -- Observable sequence. predicate -- [optional] A predicate function to evaluate for elements in the source sequence. default_value -- [Optional] The default value if no such element exists. If not specified, defaults to None. Returns: A function that takes an observable source and reutrn an observable sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. """ if predicate: return compose(ops.filter(predicate), ops.first_or_default(None, default_value)) return first_or_default_async_(True, default_value)
def create(): def predicate(x: int) -> bool: invoked[0] += 1 if x > 5: raise Exception(ex) return is_prime(x) return xs.pipe(filter(predicate))
def action(scheduler, state): def predicate(x): invoked[0] += 1 if x == 8: d.dispose() return is_prime(x) ys[0] = xs.pipe(filter(predicate)) return ys[0]
def contains_( value: _T, comparer: Optional[typing.Comparer[_T]] = None ) -> Callable[[Observable[_T]], Observable[bool]]: comparer_ = comparer or default_comparer def predicate(v: _T) -> bool: return comparer_(v, value) return compose( ops.filter(predicate), ops.some(), )
def all_( predicate: Predicate[_T] ) -> Callable[[Observable[_T]], Observable[bool]]: def filter(v: _T): return not predicate(v) def mapping(b: bool) -> bool: return not b return compose( ops.filter(filter), ops.some(), ops.map(mapping), )
def count_( predicate: Optional[Predicate[_T]] = None, ) -> Callable[[Observable[_T]], Observable[int]]: if predicate: return compose( ops.filter(predicate), ops.count(), ) def reducer(n: int, _: _T) -> int: return n + 1 counter = ops.reduce(reducer, seed=0) return counter
def buffer_with_count(source: Observable[_T]) -> Observable[List[_T]]: nonlocal skip if skip is None: skip = count def mapper(value: Observable[_T]) -> Observable[List[_T]]: return value.pipe( ops.to_list(), ) def predicate(value: List[_T]) -> bool: return len(value) > 0 return source.pipe( ops.window_with_count(count, skip), ops.flat_map(mapper), ops.filter(predicate), )
def some(source: Observable[_T]) -> Observable[bool]: """Partially applied operator. Determines whether some element of an observable sequence satisfies a condition if present, else if some items are in the sequence. Example: >>> obs = some(source) Args: predicate -- A function to test each element for a condition. Returns: An observable sequence containing a single element determining whether some elements in the source sequence pass the test in the specified predicate if given, else if some items are in the sequence. """ def subscribe( observer: abc.ObserverBase[bool], scheduler: Optional[abc.SchedulerBase] = None, ): def on_next(_: _T): observer.on_next(True) observer.on_completed() def on_error(): observer.on_next(False) observer.on_completed() return source.subscribe(on_next, observer.on_error, on_error, scheduler=scheduler) if predicate: return source.pipe( ops.filter(predicate), some_(), ) return Observable(subscribe)
def last_or_default(source: Observable[Any]) -> Observable[Any]: """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(default_value), ) return last_or_default_async(source, True, default_value)
def open(self): print("WebSocket opened") # A Subject is both an observable and observer, so we can both subscribe # to it and also feed (on_next) it with new values self.subject: Subject[Dict[str, int]] = Subject() # Now we take on our magic glasses and project the stream of bytes into # a ... query = self.subject.pipe( # 1. stream of keycodes ops.map(lambda obj: obj["keycode"]), # 2. stream of windows (10 ints long) ops.window_with_count(10, 1), # 3. stream of booleans, True or False ops.flat_map(lambda win: win.pipe(ops.sequence_equal(codes))), # 4. stream of Trues ops.filter(lambda equal: equal), ) # 4. we then subscribe to the Trues, and signal Konami! if we see any query.subscribe(on_next=lambda x: self.write_message("Konami!"))
def create(): def predicate(x: int) -> bool: invoked[0] += 1 return is_prime(x) return xs.pipe(filter(predicate))
def create() -> Observable[int]: def predicate(x: int) -> bool: invoked[0] += 1 return True return xs.pipe(filter(predicate))