subscribe method

Future<void> subscribe(
  1. String topic,
  2. PubSubMessageListener listener, [
  3. PubSubSubscribeOptions? options
])

Subscribes listener to topic.

Each listener is its own subscription: it gets the stored messages on PubSubMessageListener.onOldMessagesReceived and live ones on PubSubMessageListener.onMessageReceived, under its own options. Throws if the room has not been joined yet, the request fails, or this listener is already subscribed to topic (3073).

Example

final chat = PubSubMessageListener(
  onMessageReceived: (message) => print(message.message),
);
await room.pubSub.subscribe("CHAT", chat);

Implementation

Future<void> subscribe(String topic, PubSubMessageListener listener,
        [PubSubSubscribeOptions? options]) =>
    _lock.synchronized(() async {
      //Checked before the listener is registered: a rejected subscribe that
      //still left a handler behind would deliver messages the app never
      //successfully subscribed to.
      if (!_ensureJoined("pubSub.subscribe")) return;

      final subscriptions = _subscriptions.putIfAbsent(topic, () => {});
      if (subscriptions.containsKey(listener)) {
        throw const VideoSDKError(
          code: 3073,
          name: 'ERROR_INVALID_PARAMETER',
          message: 'You already subscribed to this topic with same listener.',
        );
      }
      final id = '${DateTime.now().microsecondsSinceEpoch}-${_nextId++}';
      subscriptions[listener] = id;
      try {
        await _pubsubSubscribe(topic, id, options?.toJson());
      } catch (_) {
        subscriptions.remove(listener);
        if (subscriptions.isEmpty) _subscriptions.remove(topic);
        rethrow;
      }
    });