pythonpython-asyncionats.io

How do I subscribe to a NATS subject in Python and keep receiving messages?


I tried out the example below (from this page):

nc = NATS()

await nc.connect(servers=["nats://demo.nats.io:4222"])

future = asyncio.Future()

async def cb(msg):
  nonlocal future
  future.set_result(msg)

await nc.subscribe("updates", cb=cb)
await nc.publish("updates", b'All is Well')
await nc.flush()

# Wait for message to come in
msg = await asyncio.wait_for(future, 1)

But this only seems useful for receiving one message. How would I subscribe and keep receiving messages?

I've also seen the package example, but it seems to just play both sides of the conversation, then quit.


Solution

  • Don't know much about python, but looks like you are just waiting for one message and program ends. You should look at the subscriber example here. As you can see, there is a loop to wait forever or for the SIGTERM signal.