connectOrReconnect method

void connectOrReconnect()

Connects or reconnects to the server with the specified headers.

Throws a StateError if this link has been disposed — a disposed link has no connectionState subject left to forward into, so rebuilding here would surface as an uncaught async Bad state from inside the socket's stream delivery instead of at the call site. Create a new WebSocketLink instead.

Implementation

void connectOrReconnect() {
  if (_isDisposed) {
    throw StateError('WebSocketLink is disposed; create a new link');
  }
  _socketClient?.dispose();
  _connectionStateSubscription?.cancel();
  _socketClient = SocketClient(
    url,
    config: config,
    protocol: subProtocol,
  );
  _connectionStateSubscription = _socketClient!.connectionState
      // The socket client's stream is a BehaviorSubject, so a listener attached after
      // construction gets the current value replayed to it. This link already seeds its own
      // subject with notConnected, so forwarding that replay would emit notConnected twice
      // per connect; drop the replay and forward every transition after it.
      .skip(1)
      .listen((state) {
    if (!_connectionState.isClosed) {
      _connectionState.add(state);
    }
  });
}