@@ -299,24 +299,30 @@ class PhoenixSocket {
299
299
/// Returns a future that completes when the reply for the sent message is
300
300
/// received. If your flow awaits for the result of this future, add a timeout
301
301
/// to it so that you are not stuck in case that the reply is never received.
302
- Future <Message > sendMessage (Message message) {
302
+ Future <Message > sendMessage (Message message) async {
303
+ return (_pendingMessages[message.ref! ] = await _sendMessage (message))
304
+ .future;
305
+ }
306
+
307
+ Future <Completer <Message >> _sendMessage (Message message) async {
308
+ if (_disposed) {
309
+ throw StateError ('Cannot add messages to a disposed socket' );
310
+ }
311
+
303
312
if (message.ref == null ) {
304
313
throw ArgumentError .value (
305
314
message,
306
315
'message' ,
307
316
'does not contain a ref' ,
308
317
);
309
318
}
310
- _addToSink (_options.serializer.encode (message));
311
- return (_pendingMessages[message.ref! ] = Completer <Message >()).future;
312
- }
313
319
314
- Future <void > _addToSink (String data) async {
315
- if (_disposed) {
316
- throw StateError ('Cannot add messages to a disposed socket' );
320
+ if (_connectionManager == null ) {
321
+ throw StateError ('Cannot add messages to a disconnected socket' );
317
322
}
318
323
319
- _connectionManager! .addMessage (data);
324
+ await _connectionManager! .addMessage (_options.serializer.encode (message));
325
+ return _pendingMessages[message.ref! ] = Completer <Message >();
320
326
}
321
327
322
328
/// CHANNELS
@@ -406,15 +412,15 @@ class PhoenixSocket {
406
412
407
413
try {
408
414
final heartbeatMessage = Message .heartbeat (nextRef);
409
- // No await here, since the heartbeat will already be completed when it
410
- // returns, and `_pendingMessages[heartbeatRef]` won't exist .
411
- sendMessage (heartbeatMessage);
415
+ // Using _sendMessages to wait for potential problems when sending message
416
+ // (eg. WebSocket failure), but not until the response is reported .
417
+ final heartbeatCompleter = await _sendMessage (heartbeatMessage);
412
418
_logger.fine ('Heartbeat ${heartbeatMessage .ref } sent' );
413
419
final heartbeatRef = _latestHeartbeatRef = heartbeatMessage.ref! ;
414
420
415
421
_heartbeatTimeout = _scheduleHeartbeat (heartbeatRef);
416
422
417
- await _pendingMessages[heartbeatRef] ! .future;
423
+ await heartbeatCompleter .future;
418
424
_logger.fine ('Heartbeat $heartbeatRef completed' );
419
425
return true ;
420
426
} on WebSocketChannelException catch (error, stackTrace) {
0 commit comments