connect method

Future<void> connect()

function to handle websocket connections

Implementation

Future<void> connect() async {
  if (_ws != null && _ws!.readyState != WebSocket.closed) {
    _ws?.close(0, 'requested reconnect');
  }

  late StreamSubscription _listener;
  _ws = await WebSocket.connect(url, headers: _headers);
  _ws!.pingInterval = Duration(seconds: 5);
  _listener = _ws!.cast<String>().map<MmWsMessage>((s) {
    var data = json.decode(s) as Map<String, dynamic>;
    if (data.containsKey('status')) return MmWsReply.fromJson(data);
    if (data.containsKey('action')) return MmWsAction(data['action'], data['data']);
    if (data.containsKey('event')) {
      // deserialize the specific event
      if (data['event'] == 'posted') {
        return MmWsEventPosted.fromJson(data);
      }
      return MmWsEvent.fromJson(data);
    }
    return MmWsReply.unknown();
  }).listen((mm) {
    _messageStreamController.add(mm);
    if (mm is MmWsEvent && onEvent != null) onEvent!(mm);
    if (mm is MmWsReply) {
      _actionCompleters[mm.seqReply]?.complete(mm);
      _actionCompleters.remove(mm.seqReply);
    }
  }, onDone: () {
    _listener.cancel();
    if (_ws!.closeReason != 'requested reconnect') {
      // this code should attempt to reconnect after an increasing delay
      // connect();
      print('Websocket Closed: ${_ws!.closeCode} ${_ws!.closeReason}');
    }
  });
}