def test_Retry_Observable_Throws(): 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 projection(x, i): selector_result = selector(x, i) if isinstance(selector_result, collections.Iterable): result = Observable.from_(selector_result) else: result = Observable.from_future(selector_result) return result
def test_repeat_observable_repeat_count_throws(): 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 case(cls, selector, sources, default_source=None, scheduler=None): """Uses selector to determine which source in sources to use. There is an alias 'switch_case'. Example: 1 - res = rx.Observable.case(selector, { '1': obs1, '2': obs2 }) 2 - res = rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0) 3 - res = rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler=scheduler) Keyword arguments: :param types.FunctionType selector: The function which extracts the value for to test in a case statement. :param list sources: A object which has keys which correspond to the case statement labels. :param Observable default_source: The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to rx.Observabe.empty with the specified scheduler. :returns: An observable sequence which is determined by a case statement. :rtype: Observable """ default_source = default_source or Observable.empty(scheduler=scheduler) def factory(): try: result = sources[selector()] except KeyError: result = default_source result = Observable.from_future(result) return result return Observable.defer(factory)
def main_reactive(): ll = _load() mm = np.array(ll) def diagonal(n, m, a): (n_axis, m_axis) = a res = [] try: for x in range(4): res.append(mm[n + x * n_axis][m + x * m_axis]) return res except IndexError: return 0, axes = ( (0, 1), (1, 0), (1, -1), (1, 1), ) Observable.from_(product(range(mm.shape[0]), range(mm.shape[1]), axes)). \ map(lambda t: diagonal(*t)) \ .map(mul_many) \ .max() \ .subscribe(print)
def if_then(cls, condition, then_source, else_source=None, scheduler=None): """Determines whether an observable collection contains values. Example: 1 - res = rx.Observable.if(condition, obs1) 2 - res = rx.Observable.if(condition, obs1, obs2) 3 - res = rx.Observable.if(condition, obs1, scheduler=scheduler) Keyword parameters: condition -- {Function} The condition which determines if the then_source or else_source will be run. then_source -- {Observable} The observable sequence or Promise that will be run if the condition function returns true. else_source -- {Observable} [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.Observabe.Empty scheduler -- [Optional] Scheduler to use. Returns an observable {Observable} sequence which is either the then_source or else_source.""" else_source = else_source or Observable.empty(scheduler=scheduler) then_source = Observable.from_future(then_source) else_source = Observable.from_future(else_source) def factory(): return then_source if condition() else else_source return Observable.defer(factory)
def test_create_with_disposable_observer_throws(self): def subscribe1(o): o.on_next(1) return Disposable.empty() def on_next(x): _raise('ex') try: return Observable.create_with_disposable(subscribe1).subscribe(on_next) except RxException: pass def subscribe2(o): o.on_error('exception') return Disposable.empty() try: return Observable.create_with_disposable(subscribe2).subscribe(on_error=lambda ex: _raise('ex')) except RxException: pass def subscribe3(o): o.on_completed() return Disposable.empty() try: return Observable.create_with_disposable(subscribe3).subscribe(on_completed=_raise('ex')) except RxException: pass
def subscribe(observer): active_plans = [] external_subscriptions = {} def on_error(err): for v in external_subscriptions.values(): v.on_error(err) observer.on_error(err) out_observer = AnonymousObserver(observer.on_next, on_error, observer.on_completed) def deactivate(active_plan): active_plans.remove(active_plan) if not len(active_plans): observer.on_completed() try: for plan in plans: active_plans.append(plan.activate(external_subscriptions, out_observer, deactivate)) except Exception as ex: Observable.throw(ex).subscribe(observer) group = CompositeDisposable() for join_observer in external_subscriptions.values(): join_observer.subscribe() group.add(join_observer) return group
async def run(sel, loop): def create_socket_observable(port, observer): sock = socket.socket() sock.bind(('localhost', port)) sock.listen(100) sock.setblocking(False) sel.register( sock, selectors.EVENT_READ, partial(accept, observer, sel) ) socket_1234 = Observable.create( partial(create_socket_observable, 1234) ) socket_1235 = Observable.create( partial(create_socket_observable, 1235) ) source = socket_1234.merge(socket_1235).share() source.subscribe( logging.info ) source.where( lambda msg: "error" in msg ).subscribe( logging.error )
def create(): return xs.join(ys, lambda x: Observable.timer(x.interval, scheduler=scheduler), lambda y: Observable.timer(y.interval, scheduler=scheduler).select_many( Observable.throw_exception(ex) if y.value == "tin" else Observable.empty()), lambda x, y: str(x.value) + y.value )
def create3(): Observable.create(throw_error).transduce( compose( filtering(even), mapping(mul10)) ).subscribe() self.assertRaises(RxException, create3)
def __init__(self, scheduler, messages): log.debug("HotObservable.__init__()") Observable.__init__(self, self._subscribe) self.scheduler = scheduler self.messages = messages self.subscriptions = AssertList() self.observers = [] observable = self def get_action(notification): def action(scheduler, state): for observer in observable.observers[:]: notification.accept(observer) return Disposable.empty() return action for message in self.messages: notification = message.value # Warning: Don't make closures within a loop action = get_action(notification) scheduler.schedule_absolute(message.time, action)
def combine_frames(*frames): result = Observable.combine_latest( frames[0], frames[1], lambda x, y: "{} {}".format(x, y)) for f in frames[2:]: result = Observable.combine_latest( result, f, lambda x, y: "{} {}".format(x, y)) return result
def scan(self): self.is_armed = not self.bluetooth.is_there_friendly_devices_nearby() self.blueStream.on_next(self.is_armed) # TODO: decouple sms alert if self.is_armed: Observable.just(True).subscribe(SmsObserver('system armed')) else: Observable.just(True).subscribe(SmsObserver('system disarmed'))
async def run(loop): Observable.timer( 0, 1000, scheduler=AsyncIOScheduler() ).tap( logging.info )
def __sense_environment(self): Observable.from_(self.sensors). \ subscribe( lambda sensor: self.working_memory.append(Fact(sensor=sensor.name, data=sensor.exec(), binding=sensor.binding)) ) Observable.from_(self.working_memory). \ subscribe( lambda fact: setattr(self.world_state, fact.binding, fact.data.output) )
def test_concat_never_never(self): scheduler = TestScheduler() e1 = Observable.never() e2 = Observable.never() def create(): return e1.concat(e2) results = scheduler.start(create) results.messages.assert_equal()
def on_next(self, img_lines): """Draw the detected lines on top of the image and display the result""" img, lines = img_lines green = (0, 255, 0) Observable.from_(lines).subscribe( lambda line: cv2.line(img, line.a, line.b, green), # on_next lambda error: print(error), # on_error lambda: self.display(img) # on_completed )
def test_let_calls_function_immediately(self): called = [False] def func(x): called[0] = True return x Observable.empty().let_bind(func) assert(called[0])
def main(): # start bluetooth scanning in the background new_bluetooth_thread = threading.Thread(target=scanner.watch) new_bluetooth_thread.daemon = True # stop if the program exits new_bluetooth_thread.start() # start listening door tag new_doortag_thread = threading.Thread(target=door_listener.listen) new_doortag_thread.daemon = True # stop if the program exits new_doortag_thread.start() # light on if pir detection or door opened door_listener.openDoorStream.merge(pirs.pirStream)\ .subscribe(LightOnObserver()) # light of after x second with no event door_listener.openDoorStream.merge(pirs.pirStream).debounce(parameters.lightup_duration*1000)\ .subscribe(LightOffObserver()) # send sms when unknown presence is detected pirs.pirStream.pausable(scanner.blueStream)\ .throttle_first(parameters.sms_min_interval_between_sms*1000).subscribe(SmsObserver('presence detected')) # send sms on open door door_listener.openDoorStream.pausable(scanner.blueStream)\ .throttle_first(parameters.sms_min_interval_between_sms*1000).subscribe(SmsObserver('door open')) # send sms on door vibe door_listener.vibeDoorStream.pausable(scanner.blueStream)\ .throttle_first(parameters.sms_min_interval_between_sms*1000).subscribe(SmsObserver('door vibe')) # turn siren when unknown presence is detected with both open door and pir # TODO: put timer duration in a variable door_listener.openDoorStream\ .join(pirs.pirStream, lambda x: Observable.timer(15*1000), lambda x: Observable.timer(15*1000), lambda x, y: True)\ .pausable(scanner.blueStream).subscribe(SirenClientObserver()) # take photo if pir detection or door opened or door vibe # TODO: more test on this # TODO: put camera interval in a variable door_listener.openDoorStream.merge(door_listener.vibeDoorStream).merge(pirs.pirStream) \ .select_many(Observable.interval(1000).take(20)).throttle_first(1000) \ .pausable(scanner.blueStream) \ .subscribe(CameraObserver()) # if the subscriber doesn't get the first blueStream event they will be paused by default # TODO: use a replay here instead of the following workaround scanner.scan() while True: # TODO: use a infinit loop instead # TODO: manage interruption time.sleep(1)
def test_skip_until_never_never(self): scheduler = TestScheduler() l = Observable.never() r = Observable.never() def create(): return l.skip_until(r) results = scheduler.start(create) results.messages.assert_equal()
def test_amb_never2(self): scheduler = TestScheduler() l = Observable.never() r = Observable.never() def create(): return l.amb(r) results = scheduler.start(create) results.messages.assert_equal()
def test_zip_never_never(self): scheduler = TestScheduler() o1 = Observable.never() o2 = Observable.never() def create(): return o1.zip(o2, lambda x, y: x + y) results = scheduler.start(create) results.messages.assert_equal()
def test_combine_latest_never_never(self): scheduler = TestScheduler() e1 = Observable.never() e2 = Observable.never() def create(): return e1.combine_latest(e2, lambda x, y: x + y) results = scheduler.start(create) results.messages.assert_equal()
def test_merge_never2(self): scheduler = TestScheduler() n1 = Observable.never() n2 = Observable.never() def create(): return Observable.merge(scheduler, n1, n2) results = scheduler.start(create) results.messages.assert_equal()
def test_merge_empty2(self): scheduler = TestScheduler() e1 = Observable.empty() e2 = Observable.empty() def create(): return Observable.merge(scheduler, e1, e2) results = scheduler.start(create) results.messages.assert_equal(on_completed(203))
def test_for_each_index_return(self): lstX = [] lstI = [] def action(x, i): lstX.append(x) lstI.append(i) Observable.return_value(42).to_blocking().for_each(action) assert(lstX == [42]) assert(lstI == [0])
def test_for_each_index_some_data(self): lstX = [] lstI = [] def action(x, i): lstX.append(x) lstI.append(i) Observable.range(10, 10).to_blocking().for_each(action) assert(lstX == [x for x in range(10, 20)]) assert(lstI == [x for x in range(10)])
def test_amb_never3(self): scheduler = TestScheduler() n1 = Observable.never() n2 = Observable.never() n3 = Observable.never() def create(): return Observable.amb(n1, n2, n3) results = scheduler.start(create) results.messages.assert_equal()
def create(): def result_selector(x, y): if x.value >= 0: raise Exception(ex) else: return str(x.value) + y.value return xs.join(ys, lambda x: Observable.timer(x.interval, scheduler=scheduler), lambda y: Observable.timer(y.interval, scheduler=scheduler), result_selector, )
def closing(): curr = window[0] window[0] += 1 return Observable.timer(curr * 100, scheduler=scheduler)
def closings(): w = window[0] window[0] += 1 return Observable.timer(w * 100, scheduler=scheduler)
def closing(x): return Observable.timer(x, scheduler=scheduler)
from __future__ import print_function from rx import Observable, Observer Observable.from_(["Alpha", "Beta", "Gamma", "Delta", "Epsilon"]) \ .map(lambda s: len(s)) \ .distinct() \ .subscribe(lambda i: print(i)) Observable.from_(["Alpha", "Beta", "Gamma", "Delta", "Epsilon"]) \ .distinct(lambda s: len(s)) \ .subscribe(lambda i: print(i))
def create(): return Observable.of(scheduler=scheduler)
from rx import Observable numbers = Observable.from_([1, 2, 3, 4]) characters = Observable.from_(['a', 'b', 'c', 'd', 'e']) Observable.zip_list(characters, numbers).subscribe( on_next=lambda i: print("on_next {}".format(i)), on_error=lambda e: print("on_error: {}".format(e)), on_completed=lambda: print("on_completed"))
def create2(): Observable.empty().transduce( compose(filtering(even), mapping(mul10))).subscribe(noop, noop, throw_error)
def sequence_equal(self, second, comparer=None): """Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. 1 - res = source.sequence_equal([1,2,3]) 2 - res = source.sequence_equal([{ "value": 42 }], lambda x, y: x.value == y.value) 3 - res = source.sequence_equal(Observable.return_value(42)) 4 - res = source.sequence_equal(Observable.return_value({ "value": 42 }), lambda x, y: x.value == y.value) second -- Second observable sequence or array to compare. comparer -- [Optional] Comparer used to compare elements of both sequences. Returns an observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. """ first = self comparer = comparer or default_comparer if isinstance(second, collections.Iterable): second = Observable.from_iterable(second) def subscribe(observer): donel = [False] doner = [False] ql = [] qr = [] def on_next1(x): if len(qr) > 0: v = qr.pop(0) try: equal = comparer(v, x) except Exception as e: observer.on_error(e) return if not equal: observer.on_next(False) observer.on_completed() elif doner[0]: observer.on_next(False) observer.on_completed() else: ql.append(x) def on_completed1(): donel[0] = True if not len(ql): if len(qr) > 0: observer.on_next(False) observer.on_completed() elif doner[0]: observer.on_next(True) observer.on_completed() def on_next2(x): if len(ql) > 0: v = ql.pop(0) try: equal = comparer(v, x) except Exception as exception: observer.on_error(exception) return if not equal: observer.on_next(False) observer.on_completed() elif donel[0]: observer.on_next(False) observer.on_completed() else: qr.append(x) def on_completed2(): doner[0] = True if not len(qr): if len(ql) > 0: observer.on_next(False) observer.on_completed() elif donel[0]: observer.on_next(True) observer.on_completed() subscription1 = first.subscribe(on_next1, observer.on_error, on_completed1) subscription2 = second.subscribe(on_next2, observer.on_error, on_completed2) return CompositeDisposable(subscription1, subscription2) return AnonymousObservable(subscribe)
from rx import Observable observable = Observable.from_([1, 2]) other_observable = Observable.from_([3, 4]) Observable.concat(observable, other_observable) \ .subscribe(on_next=lambda n: print(n)) # O/P # (1, 'LITE Industrial', 'Southwest', '729 Ravine Way', 'Irving', 'TX', 75014) # (3, 'Re-Barre Construction', 'Southwest', '9043 Windy Dr', 'Irving', 'TX', 75032) # (5, 'Marsh Lane Metal Works', 'Southeast', '9143 Marsh Ln', 'Avondale', 'LA', 79782)
from __future__ import print_function from rx import Observable foo = Observable.interval(100).take(5) foo.debounce(1000).subscribe(lambda s: print(s), on_completed=lambda : print("DONE")) input("ok\n")
from rx import Observable source1 = Observable.interval(1000).map(lambda s: "Source 1: {0}".format(s)) source2 = Observable.interval(500).map(lambda s: "Source 2: {0}".format(s)) source3 = Observable.interval(2000).map(lambda s: "Source 3: {0}".format(s)) Observable.merge(source1, source2, source3) \ .subscribe(lambda s: print(s)) input("Press key to quit\nq")
def read_request(link): f = urlopen(link) return Observable.from_(f) \ .map(lambda s: s.decode("gbk").strip())
''' 获取新浪的美股接口数据,并打印出股票名和价格 ''' from rx import Observable, Observer from urllib.request import urlopen def read_request(link): f = urlopen(link) return Observable.from_(f) \ .map(lambda s: s.decode("gbk").strip()) codes = ["usr_aapl", "usr_fb", "usr_goog", "usr_baba"] source = Observable.from_(codes)\ .map(lambda s: "http://hq.sinajs.cn/list={0}".format(s))\ .flat_map(lambda s: read_request(s)) \ .map(lambda s: s.split('"')[1]) \ .filter(lambda l: l != "") \ .map(lambda s: s.split(","))\ .map(lambda s: "股票:{0} 价格:{1}".format(s[0], s[1])) source.subscribe(on_next=lambda s: print(s)) source.count().subscribe( on_next=lambda s: print("count=", s), on_completed=lambda: print("network data source Done!\n"))
from rx import Observable source1 = Observable.interval(1000).map(lambda i: "Source 1: {0}".format(i)) source2 = Observable.interval(500).map(lambda i: "Source 2: {0}".format(i)) source3 = Observable.interval(300).map(lambda i: "Source 3: {0}".format(i)) Observable.from_([source1,source2,source3]) \ .merge_all() \ .subscribe(lambda s: print(s)) # keep application alive until user presses a key input("Press any key to quit\n")
from rx import Observable numbers = Observable.from_([1, 2, 3]) pub_numbers = numbers.publish() pub_numbers.connect() pub_numbers.subscribe(on_next=lambda i: print("item: {}".format(i)), on_error=lambda e: print("error: {}".format(e)), on_completed=lambda: print("completed")) pub_numbers.subscribe(on_next=lambda i: print("item: {}".format(i)), on_error=lambda e: print("error: {}".format(e)), on_completed=lambda: print("completed"))
def create(): return Observable.throw_exception( ex, scheduler).time_interval(scheduler)
def observable_window_with_openings(self, window_openings, window_closing_selector): return window_openings.group_join(self, window_closing_selector, lambda _: Observable.empty(), lambda _, window: window)
def test_of_empty(self): results = [] Observable.of().subscribe_(results.append) assert (len(results) == 0)
def create(): Observable.throw_exception(RxException()).transduce( compose(filtering(even), mapping(mul10))).subscribe(noop, throw_error)
def test_of(self): results = [] Observable.of(1, 2, 3, 4, 5).subscribe_(results.append) assert (str([1, 2, 3, 4, 5]) == str(results))
def create(): return Observable.empty(scheduler).time_interval(scheduler)
def create(): return Observable.amb(n1, n2, n3)
def resolve_count_seconds(root, info, up_to=5): return (Observable.interval(1000).map( lambda i: "{0}".format(i)).take_while(lambda i: int(i) <= up_to))
def create(): return Observable.never().time_interval(scheduler)
from rx import Observable if __name__ == '__main__': Observable.from_(range(2000)).buffer(Observable.interval(0.1)).subscribe( lambda buffer: print('#', len(buffer)))
def resolve_random_int(root, info): return (Observable.interval(1000).map(lambda i: RandomType( seconds=i, random_int=random.randint(0, 500))))
def word_counter(file_name): # count words using `group_by()` # tuple the word with the count return words_from_file(file_name) \ .group_by(lambda word: word) \ .flat_map(lambda grp: grp.count().map(lambda ct: (grp.key, ct))) # composes the above word_counter() into a dict def word_counter_as_dict(file_name): return word_counter(file_name).to_dict(lambda t: t[0], lambda t: t[1]) # Schedule to create a word count dict every three seconds an article # But only re-print if text is edited and word counts change article_file = "bbc_news_article.txt" # create a dict every three seconds, but only push if it changed Observable.interval(3000) \ .flat_map(lambda i: word_counter_as_dict(article_file)) .distinct_until_changed() \ .subscribe(lambda word_ct_dict: print(word_ct_dict)) # Keep alive until user presses any key input("Starting, press any key to quit\n")
def closing(): return Observable.throw_exception(ex, scheduler=scheduler)
def create(): return Observable.of(1, 2, 3, 4, 5)
#!/usr/bin/env python3 import json from rx import Observable import APIReaderTelegram as Telegram def is_message_f(element): return element['message']['text'] == "f" def pretty_print(element): print(json.dumps(element, indent=4)) messages = Observable.from_(Telegram.get_iterable()) messages.filter(is_message_f).subscribe(pretty_print)