connect method

  1. @override
Future<void> connect()
override

Implementation

@override
Future<void> connect() async {
  // print('connecting');
  try {
    _socket = WebSocketChannel.connect(
      Uri.parse(
        '$url&useOnCloseEvent=true',
      ),
    );
  } catch (e) {
    throw ReownCoreError(
      code: -1,
      message: 'No internet connection: ${e.toString()}',
    );
  }

  // Create a multi-subscription capable stream channel using stream splitting
  // This approach enables multiple listeners without broadcast streams
  final inputController = StreamController<String>.broadcast(sync: true);
  final outputController = StreamController<String>.broadcast(sync: true);

  // Split the incoming stream to support multiple listeners
  _socket!.stream.cast<String>().listen(
        (data) => inputController.add(data),
        onError: (error) => inputController.addError(error),
        onDone: () => inputController.close(),
      );

  // Route outgoing messages through the output controller
  outputController.stream.listen(
    (data) => _socket!.sink.add(data),
    onError: (error) => _socket!.sink.addError(error),
    onDone: () => _socket!.sink.close(),
  );

  _channel = StreamChannel(
    inputController.stream,
    outputController.sink,
  );

  if (_channel == null) {
    // print('Socket channel is null, waiting...');
    await Future.delayed(const Duration(milliseconds: 500));
    if (_channel == null) {
      // print('Socket channel is still null, throwing ');
      throw Exception('Socket channel is null');
    }
  }

  await _socket!.ready;

  // Check if the request was successful (status code 200)
  // try {} catch (e) {
  //   throw ReownCoreError(
  //     code: 400,
  //     message: 'WebSocket connection failed, missing or invalid project id.',
  //   );
  // }
}