demonstrateSubscriptions function
Implementation
Future<void> demonstrateSubscriptions(StompClient client) async {
// Subscribe to a destination
final subscription = await client.subscribe(
destination: '/topic/news',
ackMode: StompAckMode.client,
requestReceipt: true,
);
// Listen for messages
final messageCompleter = Completer<void>();
late StreamSubscription messageSubscription;
messageSubscription = subscription.messages.listen((message) async {
// Acknowledge the message
if (message.requiresAck && message.ackId != null) {
await client.ack(messageId: message.ackId!);
}
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);
}