Cancel Subscription
Cancel an active KubeMQ Events Store subscription cleanly after receiving events using the Rust SDK.
Overview
Every events store subscription opens a long-lived stream to the broker — an async task that keeps pulling delivered events until you tell it to stop. Calling sub.unsubscribe().await is how you release that task deliberately: shutting down a worker, rotating consumers, or tearing down a process without leaking connections or leaving a dangling stream on the server.
Internally, unsubscribe() cancels the subscription via a CancellationToken, which unwinds the receive loop and detaches from the broker-side subscription registration.
Gotchas: cancelling only stops this subscriber — the channel keeps storing every event published afterward, so nothing is lost, and a fresh subscription with StartFromFirst or a specific sequence picks up exactly where this one left off. unsubscribe().await completing doesn't guarantee every in-flight callback has finished; treat it as "no new events will start," not an instantaneous hard stop.
Prerequisites
- KubeMQ server running on
localhost:50000 - Rust SDK installed (
cargo add kubemq)
Code
use kubemq::prelude::*;
use kubemq::{EventStoreBuilder, EventsStoreSubscription};
use std::time::Duration;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
let channel = "rust-events-store.cancel-subscription";
let sub = client
.subscribe_to_events_store(
channel,
"",
EventsStoreSubscription::StartNewOnly,
|event| {
Box::pin(async move {
println!("Received: seq={}", event.sequence);
})
},
None,
)
.await?;
tokio::time::sleep(Duration::from_millis(500)).await;
let event = EventStoreBuilder::new()
.channel(channel)
.body(b"before-cancel".to_vec())
.build();
client.send_event_store(event).await?;
tokio::time::sleep(Duration::from_secs(1)).await;
sub.unsubscribe().await;
println!("Subscription cancelled");
client.close().await?;
Ok(())
}How It Works
sub.unsubscribe().awaitcancels the subscription viaCancellationToken.- Events published after cancellation are stored but not delivered to the cancelled subscriber.
- Review timeouts, channel names, and client IDs before running against shared environments.
- Run the program while the server from the prerequisites is available.
Related
Was this page helpful?