unsubscribe method

void unsubscribe(
  1. String topic, {
  2. dynamic expectAcknowledge = false,
})

Unsubscribe from a topic. Some brokers(AWS for instance) need to have each unsubscription acknowledged, use the expectAcknowledge parameter for this, default is false. For a batch subscription the topic is the first topic in the batch.

Implementation

void unsubscribe(String topic, {expectAcknowledge = false}) {
  // Get the subscription
  Subscription sub = subscriptions.values.firstWhere(
    (s) => s.topic.rawTopic == topic,
    orElse: (() => Subscription()..qos = MqttQos.reserved1),
  );
  // Check its been found, return if not
  if (sub.qos == MqttQos.reserved1) {
    MqttLogger.log(
      'SubscriptionsManager::unsubscribe '
      'Unable to find active subscription for topic $topic',
    );
    return;
  }

  // Build the message
  final messageIdentifier = messageIdentifierDispenser
      .getNextMessageIdentifier();
  final unsubscribeMsg = MqttUnsubscribeMessage().withMessageIdentifier(
    messageIdentifier,
  );
  if (expectAcknowledge) {
    unsubscribeMsg.expectAcknowledgement();
  }

  // Add the topic(s)
  if (sub.batch) {
    unsubscribeMsg.payload.subscriptions = sub.allTopics;
  } else {
    unsubscribeMsg.fromTopic(topic);
  }

  // Send the message
  connectionHandler!.sendMessage(unsubscribeMsg);

  // Create the pending subscription if acknowledge requested
  // Remove it if not.
  if (expectAcknowledge) {
    pendingUnsubscriptions[messageIdentifier] = sub;
  } else {
    subscriptions.remove(sub.messageIdentifier);
    if (onUnsubscribed != null) {
      onUnsubscribed!(topic);
    }
  }
}