renderSSE method
Render SSE (Server-Sent Events) stream to the client.
This method sets up the necessary headers for SSE and streams data to the client.
The stream
function should return a stream of strings to be sent as SSE messages.
Each message is formatted according to the SSE protocol.
The connection is kept alive until the stream is closed.
Returns a Future<String> that completes when the stream is closed.
Implementation
Future<String> renderSSE(
Stream<SSE> stream, {
ContentType? contentType,
int status = HttpStatus.ok,
Map<String, String>? headers,
SSE? finish,
}) async {
contentType ??= ContentType('text', 'event-stream', charset: 'utf-8');
headers ??= {
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no', // For Nginx
};
headers.forEach((key, value) {
response.headers.set(key, value);
});
response.statusCode = status;
response.headers.contentType = contentType;
response.bufferOutput = false;
await for (var sse in stream) {
response.write(sse.toString());
await response.flush();
}
finish ??= SSE(
event: 'end',
data: 'end',
id: '-1',
retry: 999999999999,
);
response.write(finish.toString());
await response.flush();
await response.close();
return ""; // Return empty string for SSE completion
}