-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcallback_subscriptions.py
More file actions
36 lines (26 loc) · 1.04 KB
/
callback_subscriptions.py
File metadata and controls
36 lines (26 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import asyncio
from natsrpy import Message, Nats
async def main() -> None:
"""Main function to run the example."""
nats = Nats(["nats://localhost:4222"])
await nats.startup()
async def callback(message: Message) -> None:
print(f"[FROM_CALLBACK] {message.payload!r}") # noqa: T201
# For callback subscriptions you can use detatch method.
#
# This method does the same as __enter__, however since
# it's a callback-based subscription, context managers
# are ususally not needed.
#
# But please save the reference somewhere, since python garbage
# collector might collect your detatched subscription and
# stop receiving any new messages.
cb_sub = await nats.subscribe("cb-subj", callback=callback).detatch()
await cb_sub.unsubscribe(limit=1)
nats.publish("cb-subj", "message for callback")
# Waiting for subscriber to read all the messages.
await cb_sub.wait()
# Don't forget to call shutdown.
await nats.shutdown()
if __name__ == "__main__":
asyncio.run(main())