sseMessageStream function
Decodes the message events of a Streamable HTTP SSE response bytes.
Consecutive data fields are joined with a line feed before the JSON
object is decoded. An omitted or empty event field means the message
type. Other event types, comment lines, and events carrying no data are
ignored.
A frame whose data does not decode to a JSON object arrives as a
FormatException error event. The frames behind it stay on the stream,
but await for cancels on the first error and will not reach them. An
error on bytes itself ends the stream, since there is nothing left to
read.
A frame cut short by the end of bytes is dropped. The event stream
interpretation rules ask for that, and for the UTF-8 decode algorithm,
which turns invalid bytes into the replacement character:
https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation.
Implementation
Stream<Map<String, Object?>> sseMessageStream(Stream<List<int>> bytes) =>
_sseMessageData(bytes).map<Map<String, Object?>>((source) {
final decoded = jsonDecode(source);
if (decoded is! Map<String, Object?>) {
throw FormatException(
'SSE data must be a JSON object, got ${decoded.runtimeType}',
source,
);
}
return decoded;
});