def test_select_with_index_throws(): try: return Observable.return_value(1) \ .select(lambda x, index: x) \ .subscribe(lambda x: _raise('ex')) except RxException: pass try: return Observable.throw_exception('ex') \ .select(lambda x, index: x) \ .subscribe(lambda x: x, lambda ex: _raise(ex)) except RxException: pass try: return Observable.empty() \ .select(lambda x, index: x) \ .subscribe(lambda x: x, lambda ex: _, lambda : _raise('ex')) except RxException: pass try: return Observable.create(lambda o: _raise('ex')) \ .select(lambda x, index: x) \ .subscribe() except RxException: pass
def retry(self, count=None): assert isinstance(self, Observable) if count == None: return Observable.catchFallback(itertools.repeat(self)) else: return Observable.catchFallback(itertools.repeat(self, count))
def test_repeat_observable_repeat_count_throws(self): scheduler1 = TestScheduler() xs = Observable.return_value(1, scheduler1).repeat(3) xs.subscribe(lambda x: _raise('ex')) with self.assertRaises(RxException): scheduler1.start() scheduler2 = TestScheduler() ys = Observable.throw_exception('ex1', scheduler2).repeat(3) ys.subscribe(on_error=lambda ex: _raise('ex2')) with self.assertRaises(RxException): scheduler2.start() scheduler3 = TestScheduler() zs = Observable.return_value(1, scheduler3).repeat(100) d = zs.subscribe(on_completed=lambda: _raise('ex3')) scheduler3.schedule_absolute(10, lambda sc, st: d.dispose()) scheduler3.start() xss = Observable.create(lambda o: _raise('ex4')).repeat(3) with self.assertRaises(RxException): xss.subscribe()
def repeatSelf(self, count = None): assert isinstance(self, Observable) if count == None: return Observable.concat(itertools.repeat(self)) else: return Observable.concat(itertools.repeat(self, count))
def retry(self, count = None): assert isinstance(self, Observable) if count == None: return Observable.catchFallback(itertools.repeat(self)) else: return Observable.catchFallback(itertools.repeat(self, count))
def test_select_with_index_throws(self): try: return Observable.return_value(1) \ .select(lambda x, index: x) \ .subscribe(lambda x: _raise('ex')) except RxException: pass try: return Observable.throw_exception('ex') \ .select(lambda x, index: x) \ .subscribe(lambda x: x, lambda ex: _raise(ex)) except RxException: pass try: return Observable.empty() \ .select(lambda x, index: x) \ .subscribe(lambda x: x, lambda ex: _, lambda : _raise('ex')) except RxException: pass try: return Observable.create(lambda o: _raise('ex')) \ .select(lambda x, index: x) \ .subscribe() except RxException: pass
def repeatSelf(self, count=None): assert isinstance(self, Observable) if count == None: return Observable.concat(itertools.repeat(self)) else: return Observable.concat(itertools.repeat(self, count))
def test_retry_observable_throws(self): scheduler1 = TestScheduler() xs = Observable.return_value(1, scheduler1).retry() xs.subscribe(lambda x: _raise('ex')) try: return scheduler1.start() except RxException: pass scheduler2 = TestScheduler() ys = Observable.throw_exception('ex', scheduler2).retry() d = ys.subscribe(on_error=lambda ex: _raise('ex')) scheduler2.schedule_absolute(210, lambda: d.dispose()) scheduler2.start() scheduler3 = TestScheduler() zs = Observable.return_value(1, scheduler3).retry() zs.subscribe(on_completed=lambda: _raise('ex')) try: return scheduler3.start() except RxException: pass xss = Observable.create(lambda o: _raise('ex')).retry() try: return xss.subscribe() except RxException: pass
def test_repeat_observable_repeat_count_throws(self): scheduler1 = TestScheduler() xs = Observable.return_value(1, scheduler1).repeat(3) xs.subscribe(lambda x: _raise('ex')) try: return scheduler1.start() except RxException: pass scheduler2 = TestScheduler() ys = Observable.throwException('ex1', scheduler2).repeat(3) ys.subscribe(lambda ex: _raise('ex2')) try: return scheduler2.start() except RxException: pass scheduler3 = TestScheduler() zs = Observable.return_value(1, scheduler3).repeat(100) d = zs.subscribe(on_complete=lambda: _raise('ex3')) scheduler3.schedule_absolute(10, lambda: d.dispose()) scheduler3.start() xss = Observable.create(lambda o: _raise('ex4')).repeat(3) try: return xss.subscribe() except RxException: pass
def subscribe(observer): try: result = observable_factory() except Exception as ex: return Observable.throw_exception(ex).subscribe(observer) result = Observable.from_future(result) return result.subscribe(observer)
def subscribe(observer): try: result = observable_factory() except Exception as ex: return Observable.throw_exception(ex).subscribe(observer) result = Observable.from_future(result) return result.subscribe(observer)
def _start(self, app_context, **kwargs): if self.__input is None: self.__input = app_context.inst_data_mgr.get_series(self.input.name) self.__input.subject.subscribe(on_next=self.on_update) if self.__output_bar_type == BarType.Time: current_ts = self.__clock.now() next_ts = Bar.get_next_bar_start_time(current_ts, self.__output_size) diff = next_ts - current_ts Observable.timer(int(diff), self.__output_size * 1000, self.__clock.scheduler).subscribe( on_next=self.publish)
def do_while(self, condition): """Repeats source as long as condition holds emulating a do while loop. Keyword arguments: condition -- {Function} The condition which determines if the source will be repeated. Returns an observable {Observable} sequence which is repeated as long as the condition holds.""" return Observable.concat([self, Observable.while_do(condition, self)])
def do_while(self, condition): """Repeats source as long as condition holds emulating a do while loop. Keyword arguments: condition -- {Function} The condition which determines if the source will be repeated. Returns an observable {Observable} sequence which is repeated as long as the condition holds.""" return Observable.concat([self, Observable.while_do(condition, self)])
def test_when_never_never(self): scheduler = TestScheduler() xs = Observable.never() ys = Observable.never() def create(): def selector(x, y): return x + y return Observable.when(xs.and_(ys).then_do(selector)) results = scheduler.start(create) results.messages.assert_equal()
def timeoutIndividual(self, durationSelector, firstTimeout=None, other=None): assert isinstance(self, Observable) if firstTimeout == None: firstTimeout = Observable.never() if other == None: other = Observable.throw(TimeoutException()) assert isinstance(firstTimeout, Observable) assert isinstance(other, Observable) return TimeoutObservable(self, firstTimeout, durationSelector, other)
def case(selector, sources, schedulerOrDefaultSource=None): assert callable(selector) assert isinstance(sources, dict) if schedulerOrDefaultSource == None: return Case(selector, sources, Observable.empty()) elif isinstance(schedulerOrDefaultSource, Scheduler): return Case(selector, sources, Observable.empty(schedulerOrDefaultSource)) else: assert isinstance(schedulerOrDefaultSource, Observable) return Case(selector, sources, schedulerOrDefaultSource)
def branch(condition, thenSource, schedulerOrElseSource=None): assert callable(condition) assert isinstance(thenSource, Observable) if schedulerOrElseSource == None: return If(condition, thenSource, Observable.empty()) elif isinstance(schedulerOrElseSource, Scheduler): return If(condition, thenSource, Observable.empty(schedulerOrElseSource)) else: assert isinstance(schedulerOrElseSource, Observable) return If(condition, thenSource, schedulerOrElseSource)
def test_return_observer_throws(self): scheduler1 = TestScheduler() xs = Observable.return_value(1, scheduler1) xs.subscribe(lambda x: _raise('ex')) self.assertRaises(RxException, scheduler1.start) scheduler2 = TestScheduler() ys = Observable.return_value(1, scheduler2) ys.subscribe(lambda x: x, lambda ex: ex, lambda: _raise('ex')) self.assertRaises(RxException, scheduler2.start)
def _start(self, app_context, **kwargs): if self.__input is None: self.__input = app_context.inst_data_mgr.get_series( self.input.name) self.__input.subject.subscribe(on_next=self.on_update) if self.__output_bar_type == BarType.Time: current_ts = self.__clock.now() next_ts = Bar.get_next_bar_start_time(current_ts, self.__output_size) diff = next_ts - current_ts Observable.timer( int(diff), self.__output_size * 1000, self.__clock.scheduler).subscribe(on_next=self.publish)
def test_select_throws(self): try: Observable.return_value(1) \ .select(lambda x, y: x) \ .subscribe(lambda x: _raise("ex")) except RxException: pass try: Observable.throw_exception('ex') \ .select(lambda x, y: x) \ .subscribe(on_error=lambda ex: _raise(ex)) except RxException: pass try: Observable.empty() \ .select(lambda x, y: x) \ .subscribe(lambda x: x, lambda ex: ex, lambda: _raise('ex')) except RxException: pass def subscribe(observer): _raise('ex') try: Observable.create(subscribe) \ .select(lambda x: x) \ .subscribe() except RxException: pass
def while_do(cls, condition, source): """Repeats source as long as condition holds emulating a while loop. Keyword arguments: condition -- {Function} The condition which determines if the source will be repeated. source -- {Observable} The observable sequence that will be run if the condition function returns true. Returns an observable {Observable} sequence which is repeated as long as the condition holds.""" source = Observable.from_future(source) return Observable.concat(Enumerable.while_do(condition, source))
def while_do(cls, condition, source): """Repeats source as long as condition holds emulating a while loop. Keyword arguments: condition -- {Function} The condition which determines if the source will be repeated. source -- {Observable} The observable sequence that will be run if the condition function returns true. Returns an observable {Observable} sequence which is repeated as long as the condition holds.""" source = Observable.from_future(source) return Observable.concat(Enumerable.while_do(condition, source))
def test_select_throws(): try: Observable.return_value(1) \ .select(lambda x, y: x) \ .subscribe(lambda x: _raise("ex")) except RxException: pass try: Observable.throw_exception('ex') \ .select(lambda x, y: x) \ .subscribe(on_error=lambda ex: _raise(ex)) except RxException: pass try: Observable.empty() \ .select(lambda x, y: x) \ .subscribe(lambda x: x, lambda ex: ex, lambda: _raise('ex')) except RxException: pass def subscribe(observer): _raise('ex') try: Observable.create(subscribe) \ .select(lambda x: x).dump() \ .subscribe() except RxException: pass
def take_until(self, other): """Returns the values from the source observable sequence until the other observable sequence produces a value. Keyword arguments: other -- Observable sequence that terminates propagation of elements of the source sequence. Returns an observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. """ source = self other = Observable.from_future(other) def subscribe(observer): def on_completed(x): observer.on_completed() return CompositeDisposable( source.subscribe(observer), other.subscribe(on_completed, observer.on_error, noop) ) return AnonymousObservable(subscribe)
def on_next(inner_source): d = SingleAssignmentDisposable() latest[0] += 1 _id = latest[0] has_latest[0] = True inner_subscription.disposable = d # Check if Future or Observable inner_source = Observable.from_future(inner_source) def on_next(x): if latest[0] == _id: observer.on_next(x) def on_error(e): if latest[0] == _id: observer.on_error(e) def on_completed(): 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)
def take_until(self, other): """Returns the values from the source observable sequence until the other observable sequence produces a value. Keyword arguments: other -- Observable sequence that terminates propagation of elements of the source sequence. Returns an observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. """ source = self other = Observable.from_future(other) def subscribe(observer): def on_completed(x): observer.on_completed() return CompositeDisposable( source.subscribe(observer), other.subscribe(on_completed, observer.on_error, noop)) return AnonymousObservable(subscribe)
def test_many_select_law_1(self): xs = Observable.range(1, 0) left = xs.many_select(lambda x: x.first()) right = xs left.sequence_equal(right).first().subscribe(self.assertTrue)
def merge(cls, *args): """Merges all the observable sequences into a single observable sequence. The scheduler is optional and if not specified, the immediate scheduler is used. 1 - merged = rx.Observable.merge(xs, ys, zs) 2 - merged = rx.Observable.merge([xs, ys, zs]) 3 - merged = rx.Observable.merge(scheduler, xs, ys, zs) 4 - merged = rx.Observable.merge(scheduler, [xs, ys, zs]) Returns the observable sequence that merges the elements of the observable sequences. """ if not args[0]: scheduler = immediate_scheduler sources = args[1:] elif args[0].now: scheduler = args[0] sources = args[1:] else: scheduler = immediate_scheduler sources = args[0] if isinstance(sources[0], list): sources = sources[0] return Observable.from_array(sources, scheduler).merge_observable()
def test_empty_observer_throw_exception(self): scheduler = TestScheduler() xs = Observable.empty(scheduler) xs.subscribe(lambda x: None, lambda ex: None, lambda: _raise('ex')) with self.assertRaises(RxException): scheduler.start()
def test_empty_observer_throw_exception(self): scheduler = TestScheduler() xs = Observable.empty(scheduler) xs.subscribe(lambda x: None, lambda ex: None, lambda: _raise('ex')) with self.assertRaises(RxException): scheduler.start()
def repeat(cls, value=None, repeat_count=None, scheduler=None): """Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. 1 - res = rx.Observable.repeat(42) 2 - res = rx.Observable.repeat(42, 4) 3 - res = rx.Observable.repeat(42, 4, Rx.Scheduler.timeout) 4 - res = rx.Observable.repeat(42, None, Rx.Scheduler.timeout) Keyword arguments: value -- Element to repeat. repeat_count -- [Optional] Number of times to repeat the element. If not specified, repeats indefinitely. scheduler -- Scheduler to run the producer loop on. If not specified, defaults to ImmediateScheduler. Returns an observable sequence that repeats the given element the specified number of times.""" scheduler = scheduler or current_thread_scheduler if repeat_count == -1: repeat_count = None xs = Observable.return_value(value, scheduler) return xs.repeat(repeat_count)
def merge(cls, *args): """Merges all the observable sequences into a single observable sequence. The scheduler is optional and if not specified, the immediate scheduler is used. 1 - merged = rx.Observable.merge(xs, ys, zs) 2 - merged = rx.Observable.merge([xs, ys, zs]) 3 - merged = rx.Observable.merge(scheduler, xs, ys, zs) 4 - merged = rx.Observable.merge(scheduler, [xs, ys, zs]) Returns the observable sequence that merges the elements of the observable sequences.""" if not args[0]: scheduler = immediate_scheduler sources = args[1:] elif isinstance(args[0], Scheduler): scheduler = args[0] sources = args[1:] else: scheduler = immediate_scheduler sources = args[:] if isinstance(sources[0], list): sources = sources[0] return Observable.from_array(sources, scheduler).merge_observable()
def initialize_downloadable(self, current_date): def on_next(current_datetime): self.raw_stream.on_next(self._fetch_downloadable_files(current_datetime)) Observable.interval(1000)\ .zip( self.raw_stream, self.raw_stream.filter(lambda x: len(x) > 0), lambda x, y, z: y[-1].datetime if len(y) > 0 else z[-1] )\ .subscribe(on_next) self.raw_stream.on_next([KeyWithTimeSeriese(None, self.s_date)]) self.downloadable_file_stream = self.raw_stream\ .flat_map(lambda x: Observable.from_iterable(x))\ .publish()
def time_interval(self, scheduler): """Records the time interval between consecutive values in an observable sequence. 1 - res = source.time_interval(); 2 - res = source.time_interval(Scheduler.timeout) Keyword arguments: scheduler -- [Optional] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. Return An observable sequence with time interval information on values. """ source = self scheduler = scheduler or timeout_scheduler def defer(): last = [scheduler.now()] def selector(x): now = scheduler.now() span = now - last[0] last[0] = now return TimeInterval(value=x, interval=span) return source.map(selector) return Observable.defer(defer)
def on_next(inner_source): d = SingleAssignmentDisposable() with self.lock: latest[0] += 1 _id = latest[0] has_latest[0] = True inner_subscription.disposable = d # Check if Future or Observable inner_source = Observable.from_future(inner_source) def on_next(x): if latest[0] == _id: observer.on_next(x) def on_error(e): if latest[0] == _id: observer.on_error(e) def on_completed(): 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)
def time_interval(self, scheduler): """Records the time interval between consecutive values in an observable sequence. 1 - res = source.time_interval(); 2 - res = source.time_interval(Scheduler.timeout) Keyword arguments: scheduler -- [Optional] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. Return An observable sequence with time interval information on values. """ source = self scheduler = scheduler or timeout_scheduler def defer(): last = [scheduler.now()] def selector(x): now = scheduler.now() span = now - last[0] last[0] = now return TimeInterval(value=x, interval=span) return source.select(selector) return Observable.defer(defer)
def while_do(cls, condition, source): """Repeats source as long as condition holds emulating a while loop. Keyword arguments: :param types.FunctionType condition: The condition which determines if the source will be repeated. :param Observable 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. :rtype: Observable """ source = Observable.from_future(source) return Observable.concat(Enumerable.while_do(condition, source))
def start_async(cls, function_async): """Invokes the asynchronous function, surfacing the result through an observable sequence. Keyword arguments: function_async -- {Function} Asynchronous function which returns a Future to run. Returns {Observable} An observable sequence exposing the function's result value, or an exception.""" try: future = function_async() except Exception as ex: return Observable.throw(ex) return Observable.from_future(future)
def subscribe(observer): result = None try: result = observable_factory() except Exception as ex: return Observable.throw_exception(ex).subscribe(observer) return result.subscribe(observer)
def start_async(cls, function_async): """Invokes the asynchronous function, surfacing the result through an observable sequence. Keyword arguments: function_async -- {Function} Asynchronous function which returns a Future to run. Returns {Observable} An observable sequence exposing the function's result value, or an exception.""" try: future = function_async() except Exception as ex: return Observable.throw(ex) return Observable.from_future(future)
def subscribe(observer): result = None try: result = observable_factory() except Exception as ex: return Observable.throw_exception(ex).subscribe(observer) return result.subscribe(observer)
def create(): def sel1(x, y): return x + y def sel2(x, z): return x * z def sel3(y, z): return y - z return Observable.when(xs.and_(ys).then_do(sel1), xs.and_(zs).then_do(sel2), ys.and_(zs).then_do(sel3))
def __merge(self, max_concurrent_or_other): """Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. Or merges two observable sequences into a single observable sequence. 1 - merged = sources.merge(1) 2 - merged = source.merge(otherSource) max_concurrent_or_other [Optional] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. Returns the observable sequence that merges the elements of the inner sequences. """ if isinstance(max_concurrent_or_other, int): return Observable.merge(max_concurrent_or_other) sources = self def subscribe(observer): active_count = [0] group = CompositeDisposable() is_stopped = [False] q = [] def subscribe(xs): subscription = SingleAssignmentDisposable() group.add(subscription) def on_completed(): group.remove(subscription) if q.length > 0: s = q.shift() subscribe(s) else: active_count[0] -= 1 if is_stopped[0] and active_count[0] == 0: observer.on_completed() subscription.disposable = xs.subscribe(observer.on_next, observer.on_error, on_completed) def on_next(inner_source): if active_count[0] < max_concurrent_or_other: active_count[0] += 1 subscribe(inner_source) else: q.append(inner_source) def on_completed(): is_stopped[0] = True if active_count[0] == 0: observer.on_completed() group.add(sources.subscribe(on_next, observer.on_error, on_completed)) return group return AnonymousObservable(subscribe)
def action(this, state=None): if pos[0] < len(sources): current = Observable.from_future(sources[pos[0]]) pos[0] += 1 d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = current.subscribe(observer.on_next, lambda ex: this(), lambda: this()) else: observer.on_completed()
def test_empty_observer_throw_exception(self): scheduler = TestScheduler() xs = Observable.empty(scheduler) xs.subscribe(lambda x: None, lambda ex: None, lambda: _raise('ex')) try: return scheduler.start() except RxException: pass
def create(): def on_next(x): i[0] += 1 def on_completed(): completed = True return Observable.never().do_action(on_next=on_next, on_completed=on_completed)
def create(): def predicate(x): n[0] += 1 if n[0] < 3: return True else: raise Exception(ex) return Observable.while_do(predicate, xs)
def create(): def predicate(x): n[0] += 1 if n[0] < 3: return True else: raise Exception(ex) return Observable.while_do(predicate, xs)
def test_publish_with_initial_value_multiple_connections(self): xs = Observable.never() ys = xs.publish_value(1979) connection1 = ys.connect() connection2 = ys.connect() assert (connection1 == connection2) connection1.dispose() connection2.dispose() connection3 = ys.connect() assert (connection1 != connection3)
def test_replay_time_multiple_connections(self): xs = Observable.never() ys = xs.replay(None, None, 100) connection1 = ys.connect() connection2 = ys.connect() assert(connection1 == connection2) connection1.dispose() connection2.dispose() connection3 = ys.connect() assert(connection1 != connection3)
def timeoutAbsolute(self, dueTime, other=None, scheduler=Scheduler.timeBasedOperation): assert isinstance(self, Observable) assert isinstance(scheduler, Scheduler) if other == None: other = Observable.throw(TimeoutException()) assert isinstance(other, Observable) return TimeoutAbsolute(self, dueTime, other, scheduler)
def test_select_with_index_throws(self): with self.assertRaises(RxException): return Observable.return_value(1) \ .select(lambda x, index: x) \ .subscribe(lambda x: _raise('ex')) with self.assertRaises(RxException): return Observable.throw_exception('ex') \ .select(lambda x, index: x) \ .subscribe(lambda x: x, lambda ex: _raise(ex)) with self.assertRaises(RxException): return Observable.empty() \ .select(lambda x, index: x) \ .subscribe(lambda x: x, lambda ex: _, lambda : _raise('ex')) with self.assertRaises(RxException): return Observable.create(lambda o: _raise('ex')) \ .select(lambda x, index: x) \ .subscribe()
def on_error(exception): try: result = handler(exception) except Exception as ex: observer.on_error(ex) return result = Observable.from_future(result) d = SingleAssignmentDisposable() subscription.disposable = d d.disposable = result.subscribe(observer)