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

    1. Dispatcher d = nc.createDispatcher((msg) -> {
    2. String str = new String(msg.getData(), StandardCharsets.UTF_8);
    3. System.out.println(str);
    4. });
    5. // Sync Subscription
    6. Subscription sub = nc.subscribe("updates");
    7. sub.unsubscribe();
    8. // Async Subscription
    9. d.subscribe("updates");
    10. d.unsubscribe("updates");

    JavaScript

    Python

    1. nc = NATS()
    2. await nc.connect(servers=["nats://demo.nats.io:4222"])
    3. future = asyncio.Future()
    4. async def cb(msg):
    5. nonlocal future
    6. future.set_result(msg)
    7. sid = await nc.subscribe("updates", cb=cb)
    8. await nc.publish("updates", b'All is Well')
    9. # Won't be received...
    10. await nc.publish("updates", b'...')

    TypeScript

    1. // set up a subscription to process a request
    2. let sub = await nc.subscribe(createInbox(), (err, msg) => {
    3. if (msg.reply) {
    4. nc.publish(msg.reply, new Date().toLocaleTimeString());
    5. } else {
    6. t.log('got a request for the time, but no reply subject was set.');
    7. }
    8. });
    9. // without arguments the subscription will cancel when the server receives it

    C