disconnect method

void disconnect()

Implementation

void disconnect() {
  if (socket == null) {
    Logs.debug("Socket already null, nothing to disconnect", tag: 'socket');
    return;
  }

  final socketId = socket!.id;
  Logs.info("Disconnecting socket ID: $socketId", tag: 'socket');

  // Cancel any pending reconnection
  _cancelReconnectionTimer();

  // Clear the queue
  if (_emitQueue.isNotEmpty) {
    Logs.warning("Clearing ${_emitQueue.length} queued emit(s) on disconnect",
        tag: 'socket');
    _emitQueue.clear();
  }

  try {
    // First disconnect, then dispose
    if (socket!.connected) {
      socket!.disconnect();
      Logs.debug("Socket disconnected", tag: 'socket');
    }
    socket!.dispose();
    Logs.debug("Socket disposed", tag: 'socket');
  } catch (e) {
    Logs.logError("Error during socket disconnect", tag: 'socket', error: e);
  } finally {
    // Always clean up state regardless of errors
    socket = null;
    _isInitialized = false;
    _isConnecting = false;
    _eventListenerRegistered = false;
    _openInteractionCalled = false;
    _lastOpenInteractionTime = null;
    _reconnectionAttempts = 0;
    _eventCallback = null;
    Logs.info("Socket state cleaned up successfully", tag: 'socket');
  }
}