Unsubscribing After N Messages
The message count you provide is the total message count for a subscriber. So if you unsubscribe with a count of 1, the server will stop sending messages to that subscription after it has received one message. If the subscriber has already received one or more messages, the unsubscribe will be immediate. This action based on history can be confusing if you try to auto-unsubscribe on a long running subscription, but is logical for a new one.
Auto-unsubscribe is based on the total messages sent to a subscriber, not just the new ones. Most of the client libraries also track the max message count after an auto-unsubscribe request. On reconnect, this enables clients to resend the unsubscribe with an updated total.
Go
Java
Dispatcher d = nc.createDispatcher((msg) -> {
String str = new String(msg.getData(), StandardCharsets.UTF_8);
System.out.println(str);
});
// Sync Subscription
Subscription sub = nc.subscribe("updates");
sub.unsubscribe(1);
// Async Subscription
d.subscribe("updates");
d.unsubscribe("updates", 1);
nc.close();
Python
nc = NATS()
await nc.connect(servers=["nats://demo.nats.io:4222"])
async def cb(msg):
print(msg)
sid = await nc.subscribe("updates", cb=cb)
await nc.auto_unsubscribe(sid, 1)
await nc.publish("updates", b'All is Well')
Ruby
// `max` specifies the number of messages that the server will forward
// The server will auto-cancel
let opts = {max: 10};
let sub = await nc.subscribe(createInbox(), (err, msg) => {
t.log(msg.data);
}, opts);
// another way after 10 messages
let sub2 = await nc.subscribe(createInbox(), (err, msg) => {
t.log(msg.data);
});
// if the subscription already received 10 messages, the handler
C