unsubscribeByTopicAndListener method

Future<void> unsubscribeByTopicAndListener(
  1. String topic,
  2. SubscriptionFunc listener
)

Unsubscribe from all subscriptions matching the specified topic and listener function.

This method is no-op if there are no active subscription with the specified topic and listener.

The related sse connection will be autoclosed if after the unsubscribe operation there are no active subscriptions left.

Implementation

Future<void> unsubscribeByTopicAndListener(
  String topic,
  SubscriptionFunc listener,
) async {
  var needToSubmit = false;

  final subs = _getSubscriptionsByTopic(topic);

  for (final key in subs.keys) {
    if (_subscriptions[key]?.isEmpty ?? true) {
      continue; // nothing to unsubscribe from
    }

    final beforeLength = _subscriptions[key]?.length ?? 0;

    _subscriptions[key]?.removeWhere((fn) => fn == listener);

    final afterLength = _subscriptions[key]?.length ?? 0;

    // no changes
    if (beforeLength == afterLength) {
      continue;
    }

    // mark for subscriptions change submit if there are no other listeners
    if (!needToSubmit && afterLength == 0) {
      needToSubmit = true;
    }
  }

  // no other subscriptions -> close the sse connection
  if (!_hasNonEmptyTopic()) {
    return _disconnect();
  }

  // otherwise - notify the server about the subscription changes
  // (if there are no other subscriptions in the topic)
  if (_clientId.isNotEmpty && needToSubmit) {
    return _submitSubscriptions();
  }
}