Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -945,7 +945,7 @@ class NetworkService with WidgetsBindingObserver {
}

_notifyConnectionStatusChanged(false, info: userFriendlyMessage);
_disposeInternals();
_disposeInternals(markDisposed: false);
onDisconnected?.call();
}

Expand All @@ -958,11 +958,13 @@ class NetworkService with WidgetsBindingObserver {
_disposeInternals();
}

void _disposeInternals() {
if (_disposed) {
return;
void _disposeInternals({bool markDisposed = true}) {
if (markDisposed) {
if (_disposed) {
return;
}
_disposed = true;
}
_disposed = true;

try {
_clientSocket?.destroy();
Expand Down Expand Up @@ -1000,11 +1002,26 @@ class NetworkService with WidgetsBindingObserver {

_messageQueue.clear();
_isProcessingMessages = false;
if (_protocolHandshakeCompleter != null &&
!_protocolHandshakeCompleter!.isCompleted) {
_protocolHandshakeCompleter!.complete(false);
}
_protocolHandshakeCompleter = null;
_heartbeatStarted = false;
_isReconnecting = false;
_messagesSent = 0;
_messagesReceived = 0;
_reconnectAttempts = 0;
_opponentAddress = null;
_opponentPort = null;
_lastConnectionTime = null;

logger.i("$_logTag Network disposed");
if (!markDisposed) {
_disposed = false;
logger.i("$_logTag Network connection reset");
Comment on lines 1002 to +1021

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Guard _disposeInternals against re-entrancy

The new _disposeInternals({bool markDisposed = true}) skips setting _disposed when markDisposed is false and immediately resets it to false at the end. _handleDisconnection now calls this method with markDisposed: false, so during teardown the service never enters a disposed state. Socket listeners (onError, onDone) and heartbeat timers check _disposed before invoking _handleDisconnection, meaning multiple callbacks that fire during the same disconnect will all pass the check and re-enter the teardown logic. This can invoke onDisconnected and UI updates multiple times and race concurrent clean‑ups. To keep the service reusable while still preventing repeated work, _disposeInternals should temporarily mark _disposed true while cleaning up and only set it back to false after the reset completes.

Useful? React with 👍 / 👎.

} else {
logger.i("$_logTag Network disposed");
}
}

/// Returns the first non-loopback IPv4 address, or null if not found.
Expand Down
Loading