Ending Subscriptions

The AMPS server continues a subscription until the client explicitly ends the subscription (that is, unsubscribes) or until the connection to the client is closed.

With a MessageStream, AMPS automatically unsubscribes to the topic when there are no more references to the MessageStream. You can also call the close() method on the MessageStream object to remove the subscription.

With asynchronous message processing, when a subscription is successfully made, messages will begin flowing to the message handler function and the subscribe() or execute_async() call returns a string that serves as the identifier for this subscription. A Client can have any number of active subscriptions, and this subscription ID is how AMPS designates messages intended for this subscription. To unsubscribe, we simply call unsubscribe with the subscription identifier, as shown below:

client = Client("exampleClient")

# Register an asynchronous subscription
subId = client.execute_async(
    Command("subscribe").set_topic("messages"),
    on_message_printer
)

...

# when the program is done with the subscription, unsubscribe
client.unsubscribe(subId)

In this example we use the execute_async() method to create a subscription to the messages topic. When our application is done listening to this topic, it unsubscribes (on the last line) by passing in the subscription identifier returned by the subscribe command. After the subscription is removed, no more messages will flow into our on_message_printer function.

When an application calls unsubscribe(), the client sends an explicit unsubscribe command to AMPS. The AMPS server removes that subscription from the set of subscriptions for the client, and stops sending messages for that subscription. On the client side, the client unregisters the subscription so that the MessageStream or message handler for that subscription will no longer receive messages for that subscription.

Notice that calling unsubscribe does not destroy messages that the server has already sent to the client. If there are messages on the way to the client for this subscription, the AMPS client must consume those messages. If a last_chance_message_handler is registered, the handler may receive the messages. Otherwise, they will be discarded since no message handler matches the subscription ID on the message.

Last updated