Unsubscribing
This process requires an interaction with the server, so for an asynchronous subscription there may be a small window of time where a message comes through as the unsubscribe is processed by the library. Ignoring that slight edge case, the client library will clean up any outstanding messages and tell the server that the subscription is no longer used.
Go
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();
// Async Subscription
d.subscribe("updates");
d.unsubscribe("updates");
JavaScript
Python
nc = NATS()
await nc.connect(servers=["nats://demo.nats.io:4222"])
future = asyncio.Future()
async def cb(msg):
nonlocal future
future.set_result(msg)
sid = await nc.subscribe("updates", cb=cb)
await nc.publish("updates", b'All is Well')
# Won't be received...
await nc.publish("updates", b'...')
TypeScript
// set up a subscription to process a request
let sub = await nc.subscribe(createInbox(), (err, msg) => {
if (msg.reply) {
nc.publish(msg.reply, new Date().toLocaleTimeString());
} else {
t.log('got a request for the time, but no reply subject was set.');
}
});
// without arguments the subscription will cancel when the server receives it
C