示例#1
0
def subscribe_and_wait(observable: Observable,
                       on_error: Optional[typing.OnError] = None,
                       on_completed: Optional[typing.OnCompleted] = None,
                       on_next: Optional[typing.OnNext] = None,
                       scheduler: Optional[typing.Scheduler] = None):
    disposed = threading.Event()

    def _on_next(value):
        if on_next:
            on_next(value)

    def _on_error(error):
        if on_error:
            on_error(error)
        disposed.set()

    def _on_completed():
        if on_completed:
            on_completed()
        disposed.set()

    observable.subscribe(on_next=_on_next,
                         on_error=_on_error,
                         on_completed=_on_completed,
                         scheduler=scheduler)
    disposed.wait()
示例#2
0
    def wait_for(self, observable: rx.Observable):
        # Error if not on this loop
        if (self != self.loop_service.get_loop()):
            raise Exception(
                "Loop.wait_for can only be called from the thread that the loop is running on."
            )

        # Completed status
        completed = False

        # Observable value
        value = None

        # Callback for when our task is completed
        def callback(v):
            nonlocal completed
            nonlocal value
            completed = True
            value = v
            self.run(lambda: None)

        # Subscribe to the observable
        observable.subscribe(callback)

        # Keep doing things until we are done
        while not completed and self.is_alive():
            self.do_next()

        # Did it complete?
        if (not completed):
            raise Exception(
                "Loop.wait_for was canceled as the loop has been stopped.")

        # Done, get the value
        return value
示例#3
0
    def _buffer_until_complete(source: rx.Observable):
        def do_boundary():
            boundary.on_next(0)
            boundary.on_completed()

        boundary = subject.Subject()
        source.subscribe(on_completed=do_boundary)
        return operators.buffer(boundary)(source)
示例#4
0
    def observable_to_list(observable: Observable) -> list:
        res = []

        def on_next(_list):
            nonlocal res
            res += [_list]

        def on_error(e):
            raise e

        observable.subscribe(on_next=on_next, on_error=on_error)

        return res
示例#5
0
    def __init__(self,
                 userid: str,
                 is_attending: bool,
                 attend_notifier: Observable,
                 absence_due_second: int = 3):
        self.userid = userid
        self.is_attending = is_attending
        self.schedule_obj = None
        if is_attending:
            self.detect_attendance(userid)

        self.absence_due_second = absence_due_second
        self.subject = Subject()
        attend_notifier.subscribe(self.detect_attendance)
    def __init__(self, observable: Observable, scheduler: VirtualTimeScheduler = TestScheduler()) -> None:
        super().__init__()
        self.completed = threading.Event()
        self.messages = []

        def on_next(value) -> None:
            self.messages.append(Recorded(scheduler.clock, OnNext(value)))

        def on_error(error) -> None:
            self.messages.append(Recorded(scheduler.clock, OnError(error)))
            self.completed.set()

        def on_completed() -> None:
            self.messages.append(Recorded(scheduler.clock, OnCompleted()))
            self.completed.set()

        observable.subscribe(
            on_next=on_next,
            on_error=on_error,
            on_completed=on_completed
        )
示例#7
0
async def test_heartbeat(
    test: BaseHealthWatchdogTests,
    health_obs: Observable,
    source: Observable,
    factory: Callable[[str], Any],
):
    """
    :param health_obs: Observable[BasicHealthModel], the observable of the heartbeat events
    :param source: Observable[SourceType], the observable that should trigger heartbeat events
    :param factory: Callable[[str], SourceType], a factory function that returns an object of
        the source observable sequence type
    """
    health = None

    def assign(v):
        nonlocal health
        health = v

    health_obs.subscribe(assign)

    source.on_next(factory("test_id"))
    test.scheduler.advance_by(0)
    test.assertEqual(health.health_status, ttm.HealthStatus.HEALTHY)
    test.assertEqual(health.id_, "test_id")

    # it should not be dead yet
    test.scheduler.advance_by(HealthWatchdog.LIVELINESS / 2)
    test.assertEqual(health.health_status, ttm.HealthStatus.HEALTHY)
    test.assertEqual(health.id_, "test_id")

    # # it should be dead now because the time between states has reached the threshold
    test.scheduler.advance_by(HealthWatchdog.LIVELINESS / 2)
    test.assertEqual(health.health_status, ttm.HealthStatus.DEAD)
    test.assertEqual(health.id_, "test_id")

    # # it should become alive again when a new state is emitted
    source.on_next(factory("test_id"))
    test.assertEqual(health.health_status, ttm.HealthStatus.HEALTHY)
    test.assertEqual(health.id_, "test_id")
示例#8
0
def _disposable_and_async_gen_from_obs(obs: Observable):
    """
    Compatability layer for legacy Observable to async generator

    This should be removed and subscription resolvers changed to
    return async generators after removal of flask & gevent based dagit.
    """
    queue: Queue = Queue()

    disposable = obs.subscribe(on_next=queue.put_nowait)

    async def async_gen():
        while True:
            i = await queue.get()
            yield i

    return disposable, async_gen()
示例#9
0
文件: rmf_io.py 项目: lijian8/rmf-web
    def _init_room(self, topic: str, source: rx.Observable):
        """
        :param source: rx.Observable[Mapping[str, Any]].
            The mapping values must be json serializable.
        """
        records = cast(Dict[str, Any], {})
        self.room_records[topic] = records

        def on_next(new_records: Mapping[str, Any]):
            records.update(new_records)

            async def emit_task():
                for v in new_records.values():
                    await self.sio.emit(topic, v, to=topic)
                self.logger.debug(f'emitted message to room "{topic}"')

            self.loop.create_task(emit_task())

        self._subscriptions.append(source.subscribe(on_next))
示例#10
0
    def _save_event(source: Observable, dic, key_mapper: Callable[[Any], str]):
        def on_next(data):
            dic[key_mapper(data)] = data

        source.subscribe(on_next)