def _if_then(condition: Callable[[], bool], then_source: Observable, else_source: Observable = None) -> Observable: """Determines whether an observable collection contains values. Example: 1 - res = rx.if_then(condition, obs1) 2 - res = rx.if_then(condition, obs1, obs2) Args: condition: The condition which determines if the then_source or else_source will be run. then_source: The observable sequence or Promise that will be run if the condition function returns true. else_source: [Optional] The observable sequence or Promise that will be run if the condition function returns False. If this is not provided, it defaults to rx.empty Returns: An observable sequence which is either the then_source or else_source. """ else_source = else_source or rx.empty() then_source = rx.from_future(then_source) if is_future(then_source) else then_source else_source = rx.from_future(else_source) if is_future(else_source) else else_source def factory(_: abc.Scheduler): return then_source if condition() else else_source return rx.defer(factory)
def on_next(inner_source: Observable): nonlocal source d = SingleAssignmentDisposable() with source.lock: latest[0] += 1 _id = latest[0] has_latest[0] = True inner_subscription.disposable = d # Check if Future or Observable inner_source = from_future(inner_source) if is_future(inner_source) else inner_source def on_next(x: Any) -> None: if latest[0] == _id: observer.on_next(x) def on_error(e: Exception) -> None: if latest[0] == _id: observer.on_error(e) def on_completed() -> None: if latest[0] == _id: has_latest[0] = False if is_stopped[0]: observer.on_completed() d.disposable = inner_source.subscribe_(on_next, on_error, on_completed, scheduler=scheduler)
def _take_until(other: Observable) -> Callable[[Observable], Observable]: other = from_future(other) if is_future(other) else other def take_until(source: Observable) -> Observable: """Returns the values from the source observable sequence until the other observable sequence produces a value. Args: source: The source observable sequence. Returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. """ def subscribe(observer, scheduler=None): def on_completed(_): observer.on_completed() return CompositeDisposable( source.subscribe(observer), other.subscribe_(on_completed, observer.on_error, noop, scheduler) ) return Observable(subscribe) return take_until
def subscribe(observer, scheduler=None): try: result = observable_factory(scheduler) except Exception as ex: # By design. pylint: disable=W0703 return throw(ex).subscribe(observer) result = from_future(result) if is_future(result) else result return result.subscribe(observer, scheduler=scheduler)
def projection(x, i): mapper_result = mapper(x) if mapper else mapper_indexed(x, i) if isinstance(mapper_result, collections.abc.Iterable): result = from_(mapper_result) else: result = from_future(mapper_result) if is_future( mapper_result) else mapper_result return result
def factory(_) -> Observable: try: result = sources[mapper()] except KeyError: result = default_source result = from_future(result) if is_future(result) else result return result
def func(i): source = sources[i] sad = SingleAssignmentDisposable() source = from_future(source) if is_future(source) else source def on_next(x): queues[i].append(x) next(i) sad.disposable = source.subscribe_(on_next, observer.on_error, lambda: done(i), scheduler) subscriptions[i] = sad
def on_error(exception): try: result = handler(exception, source) except Exception as ex: # By design. pylint: disable=W0703 observer.on_error(ex) return result = rx.from_future(result) if is_future(result) else result d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer, scheduler=scheduler)
def on_error(exception): try: result = handler(exception, source) except Exception as ex: # By design. pylint: disable=W0703 observer.on_error(ex) return result = rx.from_future(result) if is_future(result) else result d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer, scheduler=scheduler)
def func(i): source = sources[i] sad = SingleAssignmentDisposable() source = from_future(source) if is_future(source) else source def on_next(x): queues[i].append(x) next(i) sad.disposable = source.subscribe_(on_next, observer.on_error, lambda: done(i), scheduler) subscriptions[i] = sad
def exec(self, func, items): observables: List[rx.Observable] = [] with ProcessPoolExecutor() as executor: for item in items.values(): _future = executor.submit(func, item) observables.append(rx.from_future(_future)) all_observables = rx.merge(*observables) all_observables.subscribe( self._on_success, self._on_error, self._on_complete, )
def _skip_until(other: Observable) -> Callable[[Observable], Observable]: """Returns the values from the source observable sequence only after the other observable sequence produces a value. Args: other: The observable sequence that triggers propagation of elements of the source sequence. Returns: An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. """ other = rx.from_future(other) if is_future(other) else other def skip_until(source: Observable) -> Observable: def subscribe(observer, scheduler=None): is_open = [False] def on_next(left): if is_open[0]: observer.on_next(left) def on_completed(): if is_open[0]: observer.on_completed() subs = source.subscribe_(on_next, observer.on_error, on_completed, scheduler) subscriptions = CompositeDisposable(subs) right_subscription = SingleAssignmentDisposable() subscriptions.add(right_subscription) def on_next2(x): is_open[0] = True right_subscription.dispose() def on_completed2(): right_subscription.dispose() right_subscription.disposable = other.subscribe_( on_next2, observer.on_error, on_completed2, scheduler) return subscriptions return Observable(subscribe) return skip_until
def while_do(source: Observable) -> Observable: """Repeats source as long as condition holds emulating a while loop. Args: source: The observable sequence that will be run if the condition function returns true. Returns: An observable sequence which is repeated as long as the condition holds. """ source = rx.from_future(source) if is_future(source) else source return rx.concat_with_iterable(itertools.takewhile(condition, (source for x in infinite())))
def while_do(source: Observable) -> Observable: """Repeats source as long as condition holds emulating a while loop. Args: source: The observable sequence that will be run if the condition function returns true. Returns: An observable sequence which is repeated as long as the condition holds. """ source = rx.from_future(source) if is_future(source) else source return rx.concat( itertools.takewhile(condition, (source for x in infinite())))
def go(): future = Future() source = rx.from_future(future) def on_next(x): success[0] = False def on_error(err): success[1] = type(err) == asyncio.CancelledError def on_completed(): success[2] = False source.subscribe(on_next, on_error, on_completed) future.cancel()
def _if_then( condition: Callable[[], bool], then_source: Union[Observable, Future], else_source: Union[None, Observable, Future] = None) -> Observable: """Determines whether an observable collection contains values. Example: 1 - res = rx.if_then(condition, obs1) 2 - res = rx.if_then(condition, obs1, obs2) Args: condition: The condition which determines if the then_source or else_source will be run. then_source: The observable sequence or Promise that will be run if the condition function returns true. else_source: [Optional] The observable sequence or Promise that will be run if the condition function returns False. If this is not provided, it defaults to rx.empty Returns: An observable sequence which is either the then_source or else_source. """ else_source = else_source or rx.empty() then_source = rx.from_future(cast( Future, then_source)) if is_future(then_source) else then_source else_source = rx.from_future(cast( Future, else_source)) if is_future(else_source) else else_source def factory(_: Scheduler): return then_source if condition() else else_source return rx.defer(factory)
def go(): future = Future() future.set_result(42) source = rx.from_future(future) def on_next(x): success[0] = x == 42 def on_error(err): success[1] = False def on_completed(): success[2] = True source.subscribe(on_next, on_error, on_completed)
def on_next(inner_source): inner_subscription = SingleAssignmentDisposable() group.add(inner_subscription) inner_source = from_future(inner_source) if is_future(inner_source) else inner_source @synchronized(source.lock) def on_completed(): group.remove(inner_subscription) if is_stopped[0] and len(group) == 1: observer.on_completed() on_next = synchronized(source.lock)(observer.on_next) on_error = synchronized(source.lock)(observer.on_error) subscription = inner_source.subscribe_(on_next, on_error, on_completed, scheduler) inner_subscription.disposable = subscription
def go(): future = Future() future.set_result(42) source = rx.from_future(future) def on_next(x): success[0] = x == 42 def on_error(err): success[1] = False def on_completed(): success[2] = True source.subscribe(on_next, on_error, on_completed)
def _skip_until(other: Observable) -> Callable[[Observable], Observable]: """Returns the values from the source observable sequence only after the other observable sequence produces a value. Args: other: The observable sequence that triggers propagation of elements of the source sequence. Returns: An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. """ other = rx.from_future(other) if is_future(other) else other def skip_until(source: Observable) -> Observable: def subscribe(observer, scheduler=None): is_open = [False] def on_next(left): if is_open[0]: observer.on_next(left) def on_completed(): if is_open[0]: observer.on_completed() subs = source.subscribe_(on_next, observer.on_error, on_completed, scheduler) subscriptions = CompositeDisposable(subs) right_subscription = SingleAssignmentDisposable() subscriptions.add(right_subscription) def on_next2(x): is_open[0] = True right_subscription.dispose() def on_completed2(): right_subscription.dispose() right_subscription.disposable = other.subscribe_(on_next2, observer.on_error, on_completed2, scheduler) return subscriptions return Observable(subscribe) return skip_until
def go(): future = Future() future.set_result(42) source = rx.from_future(future) def on_next(x): success[0] = False def on_error(err): success[1] = False def on_completed(): success[2] = False subscription = source.subscribe(on_next, on_error, on_completed) subscription.dispose()
def go(): future = Future() future.set_result(42) source = rx.from_future(future) def on_next(x): success[0] = False def on_error(err): success[1] = False def on_completed(): success[2] = False subscription = source.subscribe(on_next, on_error, on_completed) subscription.dispose()
def action(scheduler, state=None): try: source = next(sources_) except StopIteration: observer.on_completed() return # Allow source to be a factory method taking an error source = source(state) if callable(source) else source current = rx.from_future(source) if is_future(source) else source d = SingleAssignmentDisposable() subscription.disposable = d def on_resume(state=None): scheduler.schedule(action, state) d.disposable = current.subscribe_(observer.on_next, on_resume, on_resume, scheduler)
def go(): error = Exception('woops') future = Future() future.set_exception(error) source = rx.from_future(future) def on_next(x): success[0] = False def on_error(err): success[1] = str(err) == str(error) def on_completed(): success[2] = False source.subscribe(on_next, on_error, on_completed)
def while_do(source: Union[Observable, Future]) -> Observable: """Repeats source as long as condition holds emulating a while loop. Args: source: The observable sequence that will be run if the condition function returns true. Returns: An observable sequence which is repeated as long as the condition holds. """ if is_future(source): obs = rx.from_future(cast(Future, source)) else: obs = cast(Observable, source) it = itertools.takewhile(condition, (obs for _ in infinite())) return rx.concat_with_iterable(it)
def on_next(inner_source): inner_subscription = SingleAssignmentDisposable() group.add(inner_subscription) inner_source = from_future(inner_source) if is_future( inner_source) else inner_source @synchronized(source.lock) def on_completed(): group.remove(inner_subscription) if is_stopped[0] and len(group) == 1: observer.on_completed() on_next = synchronized(source.lock)(observer.on_next) on_error = synchronized(source.lock)(observer.on_error) subscription = inner_source.subscribe_(on_next, on_error, on_completed, scheduler) inner_subscription.disposable = subscription
def go(): error = Exception('woops') future = Future() future.set_exception(error) source = rx.from_future(future) def on_next(x): success[0] = False def on_error(err): success[1] = str(err) == str(error) def on_completed(): success[2] = False source.subscribe(on_next, on_error, on_completed)
def action(scheduler, state=None): try: source = next(sources) except StopIteration: observer.on_completed() return # Allow source to be a factory method taking an error source = source(state) if callable(source) else source current = rx.from_future(source) if is_future(source) else source d = SingleAssignmentDisposable() subscription.disposable = d def on_resume(state=None): scheduler.schedule(action, state) d.disposable = current.subscribe_(observer.on_next, on_resume, on_resume, scheduler)
def on_next(inner_source): if not has_current[0]: has_current[0] = True inner_source = rx.from_future(inner_source) if is_future( inner_source) else inner_source inner_subscription = SingleAssignmentDisposable() g.add(inner_subscription) def on_completed_inner(): g.remove(inner_subscription) has_current[0] = False if is_stopped[0] and len(g) == 1: observer.on_completed() inner_subscription.disposable = inner_source.subscribe_( observer.on_next, observer.on_error, on_completed_inner, scheduler)
def on_next(inner_source): if not has_current[0]: has_current[0] = True inner_source = rx.from_future(inner_source) if is_future(inner_source) else inner_source inner_subscription = SingleAssignmentDisposable() g.add(inner_subscription) def on_completed_inner(): g.remove(inner_subscription) has_current[0] = False if is_stopped[0] and len(g) == 1: observer.on_completed() inner_subscription.disposable = inner_source.subscribe_( observer.on_next, observer.on_error, on_completed_inner, scheduler )
def get_data(self, query): """ query the data to the API and return the content filtered""" print(f"test {query}") return rx.of(self.orgs).pipe( flat_map(lambda name: print(name) or rx.from_future( self.get_org_repos(name))), flat_map(lambda rsp: Observable.from_list( self.get_info(rsp) # transform the response to a json list ).filter(lambda val: (val.get("description") is not None and ( val.get("description").lower()).find(query.lower()) != -1) or (val.get("language") is not None and (val.get("language").lower()).find(query.lower()) != -1)) .take(10) # just take 10 repos from each org ), map( lambda rsp: { "name": rsp.get("name"), "stars": str(rsp.get("stargazers_count")), "link": rsp.get("svn_url"), "description": rsp.get("description"), "language": rsp.get("language"), }), )
def request_response(self, request: Payload) -> Observable: return rx.from_future(self._rsocket.request_response(request))
def metadata_push(self, metadata: bytes) -> rx.Observable: return rx.from_future(self._rsocket.metadata_push(metadata))
def _timeout(duetime: typing.AbsoluteTime, other: Optional[Observable] = None, scheduler: Optional[typing.Scheduler] = None ) -> Callable[[Observable], Observable]: other = other or throw(Exception("Timeout")) other = from_future(other) if is_future(other) else other def timeout(source: Observable) -> Observable: """Returns the source observable sequence or the other observable sequence if duetime elapses. Examples: >>> res = timeout(source) Args: source: Source observable to timeout Returns: An obserable sequence switching to the other sequence in case of a timeout. """ def subscribe(observer, scheduler_=None): _scheduler = scheduler or scheduler_ or timeout_scheduler if isinstance(duetime, datetime): scheduler_method = _scheduler.schedule_absolute else: scheduler_method = _scheduler.schedule_relative switched = [False] _id = [0] original = SingleAssignmentDisposable() subscription = SerialDisposable() timer = SerialDisposable() subscription.disposable = original def create_timer(): my_id = _id[0] def action(scheduler, state=None): switched[0] = (_id[0] == my_id) timer_wins = switched[0] if timer_wins: subscription.disposable = other.subscribe(observer, scheduler=scheduler) timer.disposable = scheduler_method(duetime, action) create_timer() def on_next(value): send_wins = not switched[0] if send_wins: _id[0] += 1 observer.on_next(value) create_timer() def on_error(error): on_error_wins = not switched[0] if on_error_wins: _id[0] += 1 observer.on_error(error) def on_completed(): on_completed_wins = not switched[0] if on_completed_wins: _id[0] += 1 observer.on_completed() original.disposable = source.subscribe_(on_next, on_error, on_completed, scheduler_) return CompositeDisposable(subscription, timer) return Observable(subscribe) return timeout
import rx import asyncio async def foo(future): await asyncio.sleep(1) future.set_result(2) loop = asyncio.get_event_loop() done = loop.create_future() asyncio.ensure_future(foo(done)) number = rx.from_future(done) print("subscribing...") number.subscribe(lambda i: print("on_next: {}".format(i)), lambda e: print("on_error: {}".format(e)), lambda: print("on_completed")) print("staring mainloop") loop.run_until_complete(done) loop.close()
def task(term): t = loop.create_task(finder.search(term)) return rx.from_future(t)
def _timeout(duetime: typing.AbsoluteTime, other: Optional[Observable] = None, scheduler: Optional[typing.Scheduler] = None ) -> Callable[[Observable], Observable]: other = other or throw(Exception("Timeout")) other = from_future(other) if is_future(other) else other def timeout(source: Observable) -> Observable: """Returns the source observable sequence or the other observable sequence if duetime elapses. Examples: >>> res = timeout(source) Args: source: Source observable to timeout Returns: An obserable sequence switching to the other sequence in case of a timeout. """ def subscribe(observer, scheduler_=None): _scheduler = scheduler or scheduler_ or timeout_scheduler if isinstance(duetime, datetime): scheduler_method = _scheduler.schedule_absolute else: scheduler_method = _scheduler.schedule_relative switched = [False] _id = [0] original = SingleAssignmentDisposable() subscription = SerialDisposable() timer = SerialDisposable() subscription.disposable = original def create_timer(): my_id = _id[0] def action(scheduler, state=None): switched[0] = (_id[0] == my_id) timer_wins = switched[0] if timer_wins: subscription.disposable = other.subscribe(observer, scheduler=scheduler) timer.disposable = scheduler_method(duetime, action) create_timer() def on_next(value): send_wins = not switched[0] if send_wins: _id[0] += 1 observer.on_next(value) create_timer() def on_error(error): on_error_wins = not switched[0] if on_error_wins: _id[0] += 1 observer.on_error(error) def on_completed(): on_completed_wins = not switched[0] if on_completed_wins: _id[0] += 1 observer.on_completed() original.disposable = source.subscribe_(on_next, on_error, on_completed, scheduler_) return CompositeDisposable(subscription, timer) return Observable(subscribe) return timeout
def _amb(right_source: Observable): if is_future(right_source): obs = from_future(cast(Future, right_source)) else: obs = cast(Observable, right_source) def amb(left_source: Observable): def subscribe(observer: typing.Observer, scheduler: typing.Scheduler = None) -> typing.Disposable: choice = [None] left_choice = 'L' right_choice = 'R' left_subscription = SingleAssignmentDisposable() right_subscription = SingleAssignmentDisposable() def choice_left(): if not choice[0]: choice[0] = left_choice right_subscription.dispose() def choice_right(): if not choice[0]: choice[0] = right_choice left_subscription.dispose() def on_next_left(value): with left_source.lock: choice_left() if choice[0] == left_choice: observer.on_next(value) def on_error_left(err): with left_source.lock: choice_left() if choice[0] == left_choice: observer.on_error(err) def on_completed_left(): with left_source.lock: choice_left() if choice[0] == left_choice: observer.on_completed() left_d = left_source.subscribe_(on_next_left, on_error_left, on_completed_left, scheduler) left_subscription.disposable = left_d def send_right(value: Any) -> None: with left_source.lock: choice_right() if choice[0] == right_choice: observer.on_next(value) def on_error_right(err: Exception) -> None: with left_source.lock: choice_right() if choice[0] == right_choice: observer.on_error(err) def on_completed_right() -> None: with left_source.lock: choice_right() if choice[0] == right_choice: observer.on_completed() right_d = obs.subscribe_(send_right, on_error_right, on_completed_right, scheduler) right_subscription.disposable = right_d return CompositeDisposable(left_subscription, right_subscription) return Observable(subscribe) return amb
if n % 2 == 0: return False sqrt_n = int(math.floor(math.sqrt(n))) for i in range(3, sqrt_n + 1, 2): if n % i == 0: return False return True # %% if __name__ == "__main__": multiprocessing.freeze_support() with concurrent.futures.ProcessPoolExecutor() as executor: # with concurrent.futures.ThreadPoolExecutor() as executor: fut = executor.submit(is_prime, PRIMES[0]) def on_next(x): print("on_next = {}".format(x)) def on_error(err): print("on_error = {}".format(err)) def on_completed(): print("on_completed = {}".format("complete")) rx.from_future(fut).subscribe(on_next, on_error, on_completed) concurrent.futures.wait([fut]) #.result()
def intervalRead(rate, fun) -> rx.Observable: loop = asyncio.get_event_loop() return rx.interval(rate).pipe( ops.map(lambda i: rx.from_future(loop.create_task(fun()))), ops.merge_all() )
def fire_and_forget(self, request: Payload) -> rx.Observable: return rx.from_future(self._rsocket.fire_and_forget(request))
def to_observable(corutin): return from_future(asyncio.create_task(corutin))
def response_stream(loop, req_desc): return rx.from_future(loop.create_task(perform_request(req_desc))).pipe(materialize())