Skip to content

Commit

Permalink
Merge pull request #3 from foxB612/err_handle
Browse files Browse the repository at this point in the history
feat: Passing errors to the stream
  • Loading branch information
pratikbaid3 authored Jan 26, 2022
2 parents 320914d + 4f694fb commit 7549d52
Showing 1 changed file with 49 additions and 42 deletions.
91 changes: 49 additions & 42 deletions lib/flutter_client_sse.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,51 +29,58 @@ class SSEClient {
response.asStream().listen((data) {
//Applying transforms and listening to it
data.stream
..transform(Utf8Decoder())
.transform(LineSplitter())
.listen((dataLine) {
if (dataLine.isEmpty) {
//This means that the complete event set has been read.
//We then add the event to the stream
streamController.add(currentSSEModel);
currentSSEModel = SSEModel(data: '', id: '', event: '');
return;
}
//Get the match of each line through the regex
Match match = lineRegex.firstMatch(dataLine)!;
var field = match.group(1);
if (field!.isEmpty) {
return;
}
var value = '';
if (field == 'data') {
//If the field is data, we get the data through the substring
value = dataLine.substring(
5,
);
} else {
value = match.group(2) ?? '';
}
switch (field) {
case 'event':
currentSSEModel.event = value;
break;
case 'data':
currentSSEModel.data =
(currentSSEModel.data ?? '') + value + '\n';
break;
case 'id':
currentSSEModel.id = value;
break;
case 'retry':
break;
}
});
..transform(Utf8Decoder()).transform(LineSplitter()).listen(
(dataLine) {
if (dataLine.isEmpty) {
//This means that the complete event set has been read.
//We then add the event to the stream
streamController.add(currentSSEModel);
currentSSEModel = SSEModel(data: '', id: '', event: '');
return;
}
//Get the match of each line through the regex
Match match = lineRegex.firstMatch(dataLine)!;
var field = match.group(1);
if (field!.isEmpty) {
return;
}
var value = '';
if (field == 'data') {
//If the field is data, we get the data through the substring
value = dataLine.substring(
5,
);
} else {
value = match.group(2) ?? '';
}
switch (field) {
case 'event':
currentSSEModel.event = value;
break;
case 'data':
currentSSEModel.data =
(currentSSEModel.data ?? '') + value + '\n';
break;
case 'id':
currentSSEModel.id = value;
break;
case 'retry':
break;
}
},
onError: (e, s) {
// Connection error
streamController.addError(e, s);
},
);
}, onError: (e, s) {
// Connection initialization error
streamController.addError(e, s);
});
} catch (e) {
} catch (e, s) {
print('---ERROR---');
print(e);
streamController.add(SSEModel(data: '', id: '', event: ''));
streamController.addError(e, s);
}

Future.delayed(Duration(seconds: 1), () {});
Expand Down

0 comments on commit 7549d52

Please sign in to comment.