checkHealth method
Probe whether the server is actually answering on this socket.
Sends a trivial OneOffQuery and awaits the matching
OneOffQueryResult within timeout. Returns true if a response
arrives, false if the timeout elapses first OR if the connection
reports itself disconnected.
Intended for app-resume flows on mobile, where the OS may have
silently killed the socket's read-half while the app was suspended.
The SDK's built-in KeepAliveMonitor will catch this eventually
(via its own idle-ping + pong-timeout), but its timers are paused
while the app is backgrounded, so on resume there's a window where
the client believes the connection is alive but server messages
never arrive. Callers should invoke checkHealth() on resume and
call SpacetimeDbConnection.reconnect when it returns false.
Implementation
Future<bool> checkHealth({
Duration timeout = const Duration(seconds: 3),
}) async {
if (!_connection.isConnected) return false;
final requestId = _healthCheckRequestId++;
final completer = Completer<bool>();
late StreamSubscription<OneOffQueryResult> sub;
sub = onOneOffQueryResult.listen((result) {
if (result.requestId == requestId && !completer.isCompleted) {
completer.complete(true);
}
});
try {
oneOffQuery(
'SELECT * FROM __spacetime_dart_sdk_healthcheck__',
requestId: requestId,
);
return await completer.future.timeout(timeout, onTimeout: () => false);
} finally {
await sub.cancel();
}
}