Skip to content

Commit f917979

Browse files
committed
Updated callback example.
1 parent 96e9105 commit f917979

1 file changed

Lines changed: 9 additions & 1 deletion

File tree

examples/callback_subscriptions.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ async def main() -> None:
1111
async def callback(message: Message) -> None:
1212
print(f"[FROM_CALLBACK] {message.payload!r}") # noqa: T201
1313

14+
async with nats.subscribe("cb-subj", callback=callback) as sub:
15+
# Lets you unsubscribe after `n` messages.
16+
await sub.unsubscribe(limit=1)
17+
await nats.publish("cb-subj", "context-based")
18+
# Waits for subscription to be drained.
19+
# Reach limit in our case.
20+
await sub.wait()
21+
1422
# For callback subscriptions you can use detatch method.
1523
#
1624
# This method does the same as __enter__, however since
@@ -23,7 +31,7 @@ async def callback(message: Message) -> None:
2331
cb_sub = await nats.subscribe("cb-subj", callback=callback).detatch()
2432
await cb_sub.unsubscribe(limit=1)
2533

26-
nats.publish("cb-subj", "message for callback")
34+
nats.publish("cb-subj", "detached version")
2735

2836
# Waiting for subscriber to read all the messages.
2937
await cb_sub.wait()

0 commit comments

Comments
 (0)