Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to calculate continuously data using msg that from subscription, then publish generated data? #151

Open
FlamesCN opened this issue Apr 10, 2020 · 2 comments

Comments

@FlamesCN
Copy link

FlamesCN commented Apr 10, 2020

I put my code after print func, like this:

async def run(loop):
    nc = NATS()

    await nc.connect("demo.nats.io:4222", loop=loop)

    async def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))
        # MY CODE:
        while True:
              data0 = initial_some_data()
              data1, data2 = calculate_data(data, data0)
              await nc.publish('example', data1)
              data0 = data2
              

    # Simple publisher and async subscriber via coroutine.
    sid = await nc.subscribe("foo", cb=message_handler)

if __name__ == '__main__':
  loop = asyncio.get_event_loop()
  loop.get_debug()
  loop.run_until_complete(run(loop))
  loop.run_forever()

I tried to use 'while True and break' contain my code, that didn't work at all. BTW, I use pandas to calculate data.

@charliestrawn
Copy link
Collaborator

There's nothing wrong with the example code, but I wouldn't expect to see any output because you aren't publishing any messages to the subscription. This just connects to nats and listens for messages, but you never send any. If you add something like:

    await nc.publish("foo", b'Hello')
    await nc.publish("foo", b'World')
    await nc.publish("foo", b'!!!!!')

after sid = await nc.subscribe(...) you should see your handler print the messages.

@FlamesCN
Copy link
Author

My code was a simple example, the nats-server was published already by another client. I want to know how to keep my code thread-safe in the message_handler, or how to get data out of the coroutine function. Thanks for your answer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants