Skip to content

Commit

Permalink
Fixed race condition for posting messages. (flutter#11)
Browse files Browse the repository at this point in the history
Address flutter#10
  • Loading branch information
Pi Songkuntham authored Aug 28, 2019
1 parent 20567a4 commit fc168d5
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions lib/client/sse_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class SseClient extends StreamChannelMixin<String> {
_eventSource.addEventListener('message', _onIncomingMessage);
_eventSource.addEventListener('control', _onIncomingControlMessage);
_eventSource.onError.listen(_incomingController.addError);
_startPostingMessages();
}

Stream<Event> get onOpen => _eventSource.onOpen;
Expand Down Expand Up @@ -83,12 +84,21 @@ class SseClient extends StreamChannelMixin<String> {
close();
}

final _messages = StreamController<dynamic>();

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');
}
}
}
}

0 comments on commit fc168d5

Please sign in to comment.