Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Eventsource.close() method #25

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ doc/api/
*.ipr
*.iws
/.dart_tool

pubspec.lock
16 changes: 15 additions & 1 deletion lib/eventsource.dart
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ class EventSource extends Stream<Event> {

EventSourceReadyState _readyState = EventSourceReadyState.CLOSED;

StreamSubscription<void>? _httpStreamSubscription;

http.Client client;
Duration _retryDelay = const Duration(milliseconds: 3000);
String? _lastEventId;
Expand Down Expand Up @@ -86,6 +88,12 @@ class EventSource extends Stream<Event> {
_streamController.stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);

// close the event source and terminate the remote connection
Future<void> close() async {
await _httpStreamSubscription?.cancel();
await _streamController.close();
}

/// Attempt to start a new connection.
Future _start() async {
_readyState = EventSourceReadyState.CONNECTING;
Expand All @@ -109,7 +117,8 @@ class EventSource extends Stream<Event> {
}
_readyState = EventSourceReadyState.OPEN;
// start streaming the data
response.stream.transform(_decoder).listen((Event event) {
_httpStreamSubscription = response.stream.transform(_decoder).listen(
(Event event) {
_streamController.add(event);
_lastEventId = event.id;
},
Expand All @@ -125,6 +134,11 @@ class EventSource extends Stream<Event> {
Duration backoff = _retryDelay;
while (true) {
await new Future.delayed(backoff);
// stop retrying if the event source was closed
if (_streamController.isClosed) {
break;
}

try {
await _start();
break;
Expand Down