subscribe method

  1. @override
Future<void> subscribe(
  1. String filter,
  2. Qos qos
)
override

Starts receiving messages that match filter on messages.

Throws a ConnectionException if not connected.

Implementation

@override
Future<void> subscribe(String filter, Qos qos) async {
  _checkConnected();
  checkTopicFilter(filter);
  _subscriptions[filter] = qos;

  // A real broker sends retained messages after the subscribe completes,
  // so code that listens right after `await subscribe(...)` still gets
  // them. Timer.run waits until the caller's code has run.
  final retained = broker._retained.values
      .where((m) => topicMatchesFilter(filter, m.topic))
      .toList();
  if (retained.isEmpty) return;
  Timer.run(() {
    if (_subscriptions[filter] != qos) return;
    for (final message in retained) {
      _messages.add(
        RawMessage(
          message.topic,
          message.payload,
          qos: _min(message.qos, qos),
          retained: true,
        ),
      );
    }
  });
}