KubeMQ
Client SDKsElixirHow-to guidesEvents

Cancel Subscription

Cancel an active KubeMQ event subscription and stop receiving messages using the Elixir SDK.

Overview

A live Events subscription holds a background process open indefinitely, so a long-running service needs an explicit way to tear one down without closing the whole client connection — for example when a feature flag disables a channel, a worker is draining before shutdown, or a subscription needs to be re-created with different options. Calling KubeMQ.Subscription.cancel/1 stops delivery cleanly and releases those resources on both sides.

KubeMQ.Client.subscribe_to_events/3 registers the callback and returns a subscription reference immediately, so the process keeps running in the background until you cancel it. KubeMQ.Subscription.cancel/1 stops the subscription and releases server-side resources, and KubeMQ.Subscription.active?/1 gives you a way to check the current state — useful for confirming a cancellation actually took effect before moving on.

Gotchas: cancelling one subscription doesn't affect others on the same channel. Events already in flight when you cancel may still be delivered briefly afterward. And because Events are fire-and-forget, anything published after cancellation is simply dropped for this subscriber — there's no queue to catch up from later.

Prerequisites

  • KubeMQ server running on localhost:50000
  • Elixir SDK installed ({:kubemq, "~> 1.0"} in mix.exs)

Code

main.exs
channel = "elixir-events.cancel-subscription"
{:ok, client} = KubeMQ.Client.start_link(address: "localhost:50000", client_id: "elixir-events-cancel")

{:ok, sub} =
  KubeMQ.Client.subscribe_to_events(client, channel,
    on_event: fn event -> IO.puts("Got event: #{event.body}") end
  )

IO.puts("Subscription active? #{KubeMQ.Subscription.active?(sub)}")

:ok = KubeMQ.Client.send_event(client, KubeMQ.Event.new(channel: channel, body: "Before cancel"))
Process.sleep(500)

:ok = KubeMQ.Subscription.cancel(sub)
IO.puts("Subscription cancelled. Active? #{KubeMQ.Subscription.active?(sub)}")

:ok = KubeMQ.Client.send_event(client, KubeMQ.Event.new(channel: channel, body: "After cancel"))
Process.sleep(500)

IO.puts("Second event sent but no subscriber to receive it.")
KubeMQ.Client.close(client)

How It Works

  • KubeMQ.Subscription.active?/1 checks whether a subscription is still receiving events
  • KubeMQ.Subscription.cancel/1 stops the subscription and releases server resources
  • Events published after cancellation are not delivered to the cancelled subscriber

Was this page helpful?

On this page