From fc168d5d07bc7489bef4fcfdff22f51d61fa266f Mon Sep 17 00:00:00 2001 From: Pi Songkuntham Date: Wed, 28 Aug 2019 16:57:37 -0700 Subject: [PATCH] Fixed race condition for posting messages. (#11) Address #10 --- lib/client/sse_client.dart | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/client/sse_client.dart b/lib/client/sse_client.dart index ab0b0338ce2fc..0ca8092b2fea1 100644 --- a/lib/client/sse_client.dart +++ b/lib/client/sse_client.dart @@ -40,6 +40,7 @@ class SseClient extends StreamChannelMixin { _eventSource.addEventListener('message', _onIncomingMessage); _eventSource.addEventListener('control', _onIncomingControlMessage); _eventSource.onError.listen(_incomingController.addError); + _startPostingMessages(); } Stream get onOpen => _eventSource.onOpen; @@ -83,12 +84,21 @@ class SseClient extends StreamChannelMixin { close(); } + final _messages = StreamController(); + void _onOutgoingMessage(dynamic message) async { - var encoded = jsonEncode(message); - try { - await _client.post(_serverUrl, body: encoded); - } catch (e) { - _logger.warning('Unable to encode outgoing message: $e'); + _messages.add(message); + } + + void _startPostingMessages() async { + await for (var message in _messages.stream) { + try { + await _client.post(_serverUrl, body: jsonEncode(message)); + } on JsonUnsupportedObjectError catch (e) { + _logger.warning('Unable to encode outgoing message: $e'); + } on ArgumentError catch (e) { + _logger.warning('Invalid argument: $e'); + } } } }