demonstrateSubscriptions function
Implementation
Future<void> demonstrateSubscriptions(StompClient client) async {
print('\n📬 Example 2: Subscriptions and Message Delivery');
// Subscribe to a destination
final subscription = await client.subscribe(
destination: '/topic/news',
ackMode: StompAckMode.client,
requestReceipt: true,
);
print('✅ Subscribed to /topic/news with ID: ${subscription.id}');
// Listen for messages
final messageCompleter = Completer<void>();
late StreamSubscription messageSubscription;
messageSubscription = subscription.messages.listen((message) async {
print('📩 Received message:');
print(' Message ID: ${message.messageId}');
print(' Destination: ${message.destination}');
print(' Content: ${message.body}');
// Acknowledge the message
if (message.requiresAck && message.ackId != null) {
await client.ack(messageId: message.ackId!);
print('✅ Message acknowledged');
}
messageCompleter.complete();
});
// Send a message to the subscribed destination
await client.send(
destination: '/topic/news',
body: 'Breaking news: STOMP protocol working perfectly!',
contentType: 'text/plain',
);
// Wait for the message to be received
await messageCompleter.future.timeout(const Duration(seconds: 5));
await messageSubscription.cancel();
// Unsubscribe
await client.unsubscribe(subscriptionId: subscription.id);
print('✅ Unsubscribed from /topic/news');
}