3

Here is what I'm trying to achieve:

  1. Create 2 independent objects that return asynchronous messages
  2. Convert the messages in Observable

The functions are long so each object is on a separate file. Here is the base structure of my objects:

class Object:
    def message(self, observer, scheduler):
        _task = None

        def _teardown():
            if _task:
                _task.cancel()
            observer.on_completed()

        async def _loop():
            while True:
                #DO STUFF
                observer.on_next(message)

        async def _run_loop():
            try:
                await _loop()
            except asyncio.CancelledError:
                print('error')
            finally:
                _teardown()

        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        _task = loop.create_task(_run_loop())
        loop.run_forever()

Here is the code for RXPY:

object1 = Object1()

object1_observable = defer(lambda _: create(object1.message)).pipe(
    op.observe_on(EventLoopScheduler()),
    op.share()
)

object1_observable.subscribe(lambda value: print('Object1 Observer Received'))

object2 = Object2()

object2_observable = defer(lambda _: create(object2.message)).pipe(
    op.observe_on(EventLoopScheduler()),
    op.share()
)

object2_observable.subscribe(lambda value: print('Object2 Observer Received'))

Question 1: With this code, I receive messages from object1 only. How should I adapt this code to make it work and receive messages from both objects?

Question 2: I would like the messages from object1 to be parameters for another class, let's say Object3. The Object3 would then listen to Object2. For every messages from Object2, Object3 would do something. And for every messages from Object1, Object3 attributes would change. However, the attributes should not change until Object3 is done with latest message from Object2. I have no clue how to do that with RXPY. Any idea?

Update With treads, the code works. I am not sure this a good way to proceed though. I will update it with a proper killing process and I still work on question 2 too

class Object:
    def message(self, observer, scheduler):
        def _loop():
            while True:
                #DO STUFF
                observer.on_next(message)

        thread = threading.Thread(target=_loop)
        thread.daemon = False
        thread.start()
Joseph
  • 209
  • 2
  • 11
  • What you've proposed seem to have two different event loops. I understand this might be late, but maybe this article might be of some help. https://blog.oakbits.com/rxpy-and-asyncio.html – nlhnt Oct 17 '22 at 21:13

0 Answers0