Skip to content

Commit

Permalink
Update socket state accordingly and reason about at the beginning of …
Browse files Browse the repository at this point in the history
…_connect()
  • Loading branch information
miguelcmedeiros committed Apr 23, 2024
1 parent 7a94767 commit 49c79f9
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/src/socket.dart
Original file line number Diff line number Diff line change
Expand Up @@ -171,12 +171,14 @@ class PhoenixSocket {
bool get isConnected => _ws != null && _socketState == SocketState.connected;

void _connect(Completer<PhoenixSocket?> completer) async {
_logger.warning('socket state: $_socketState');
if (_ws != null &&
(_socketState != SocketState.connected ||
_socketState != SocketState.connecting)) {
(_socketState == SocketState.connected ||
_socketState == SocketState.connecting)) {
_logger.warning(
'Calling connect() on already connected or connecting socket.');
completer.complete(this);
return;
}

_shouldReconnect = true;
Expand All @@ -193,11 +195,15 @@ class PhoenixSocket {
? _webSocketChannelFactory!(_mountPoint)
: WebSocketChannel.connect(_mountPoint);

_socketState = SocketState.connecting;

// Wait for the WebSocket to be ready before continuing. In case of a
// failure to connect, the future will complete with an error and will be
// caught.
await _ws!.ready;

_socketState = SocketState.connected;

_ws!.stream
.where(_shouldPipeMessage)
.listen(_onSocketData, cancelOnError: true)
Expand All @@ -208,10 +214,8 @@ class PhoenixSocket {
}

_reconnectAttempts++;
_socketState = SocketState.connecting;

try {
_socketState = SocketState.connected;
_logger.finest('Waiting for initial heartbeat roundtrip');
if (await _sendHeartbeat(ignorePreviousHeartbeat: true)) {
_stateStreamController.add(PhoenixSocketOpenEvent());
Expand Down

0 comments on commit 49c79f9

Please sign in to comment.