Ending Subscriptions
With asynchronous message processing, when a subscription is
successfully made, messages will begin flowing to the message handler
function and the Client.subscribe()
call returns a Promise object
that resolves with a unique string that serves as the identifier for
this subscription. A Client
can have any number of active subscriptions,
and this string is used to refer to the particular subscription we have
made here. For example, to unsubscribe, we simply pass in this identifier:
const client = new Client('exampleClient');
await client.connect('wss://localhost:9000/amps/json');
const subId = await client.subscribe(onMessagePrinter, 'messages');
// when the program is done with the subscription, unsubscribe
await client.unsubscribe(subId);
console.log('Unsubscribed');
In this example, as in the previous section, we use the
Client.subscribe()
method to create a subscription to the
messages
topic. When our application is done listening to this
topic, it unsubscribes by passing in the subId
passed from the
successfully resolved Promise of subscribe()
. After the subscription
is removed, no more messages will flow into our onMessagePrinter
function.
AMPS also accepts the keyword all
to unsubscribe all subscriptions
for the client.