subscribe method

Future<Subscription> subscribe(
  1. String channel,
  2. SubscriptionCallback callback
)

Subscribe to a channel

Implementation

Future<Subscription> subscribe(
    String channel, SubscriptionCallback callback) async {
  _logger.info('Client: Subscribing to channel: $channel');
  _logger.info('Client: Current state: $_state');

  // Allow subscriptions during connecting state (2) as well as connected state (3)
  // This is needed because extensions may try to subscribe during handshake response processing
  if (_state != connected && _state != connecting) {
    _logger.severe(
        'Client: Cannot subscribe - not connected or connecting. State: $_state');
    throw FayeError.network('Not connected');
  }

  // Start connect cycle if this is the first operation after handshake
  if (_state == connected) {
    _startConnectCycle();
  }

  if (!channel.isValidChannel && !channel.isValidChannelPattern) {
    _logger.severe('Client: Invalid channel name: $channel');
    throw FayeError.channel(channel, 'Invalid channel name');
  }

  final channelObj = Channel(channel);
  final subscriptionId = _uuid.v4();

  _logger.info('Client: Calling dispatcher.subscribe()...');

  try {
    final response = await _dispatcher.subscribe(channel);
    _logger.info('Client: Dispatcher.subscribe() response: $response');

    final responseMessage = extractBayeuxMessage(response);

    if (responseMessage['successful'] == true) {
      final subscription = Subscription(
        id: subscriptionId,
        channel: channelObj,
        callback: callback,
      );

      _subscriptions[subscriptionId] = subscription;

      _logger.info('Client: Subscribed to $channel successfully');
      return subscription;
    } else {
      _logger.severe(
          'Client: Subscription to $channel failed: ${responseMessage['error']}');
      final error = responseMessage['error'];
      if (error is Map<String, dynamic>) {
        throw FayeError.fromBayeux(error);
      } else if (error is String) {
        throw FayeError.network('Subscription failed: $error');
      } else {
        throw FayeError.network('Subscription failed: Unknown error');
      }
    }
  } catch (e) {
    _logger
        .severe('Client: Subscription to $channel failed with exception: $e');
    rethrow;
  }
}