Last active
March 15, 2021 11:49
-
-
Save contrasting/460d013cbee8d326a71c8bf9e8b78b0c to your computer and use it in GitHub Desktop.
How to access EventSource (SSE) API from dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'dart:html'; | |
| class EventSourceModel { | |
| static const kEndPoint = 'https://myfirebaseendpoint.com'; | |
| EventSource es; | |
| final StreamController<UserMatch> _controller = StreamController<UserMatch>(); | |
| Stream<UserMatch> get stream => _controller.stream; | |
| EventSourceModel() { | |
| es = EventSource(kEndPoint); | |
| es.onError.listen(_onError); | |
| es.addEventListener('put', _onPut); | |
| es.addEventListener('patch', _onPatch); | |
| es.addEventListener('auth_revoked', _onAuthRevoked); | |
| } | |
| // replace all of the data at that location in its cache with the data given in the message | |
| // e.g. new match(es) | |
| void _onPut(Event e) { | |
| MessageEvent me = e as MessageEvent; | |
| Map<String, dynamic> json = jsonDecode(me.data.toString()); | |
| if (json['path'] == '/') { | |
| Map<String, dynamic> matches = json['data']; | |
| for (String matchConvoID in matches.keys) { | |
| Map<String, dynamic> matchObject = matches[matchConvoID]; | |
| _controller.add(_parseMatch(matchConvoID, matchObject)); | |
| } | |
| } else { | |
| String matchConvoID = json['path'].toString().substring(1); | |
| Map<String, dynamic> matchObject = json['data']; | |
| _controller.add(_parseMatch(matchConvoID, matchObject)); | |
| } | |
| } | |
| void _onError(Event e) { | |
| _controller.close(); | |
| } | |
| } | |
| // references: | |
| // https://developer.mozilla.org/en-US/docs/Web/API/EventSource | |
| // https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment