stream method

Future<EventSource> stream(
  1. Uri url, {
  2. Map<String, String>? headers,
  3. String? lastEventId,
  4. String verb = 'GET',
})

Send a HTTP-request that results in a stream of ServerSentEvents in form of a EventSource.

This methods makes a GET-requests (or whatever verb is set to) with the given url. It will add some additional headers to headers, leading to the server returning an "endless" stream of data in form of ServerSentEvents.

If the server supports it, and you had to cancel a stream at some point, you might be able to resume it by passing the ServerSentEvent.lastEventId of the last event that has been received to lastEventId.

If the requests succeeds, the returned future will resolve to a stream of SSEs, an EventSource. If the request does not succeed (any statuscode but 200), instead a ClientStreamException will be thrown, containing the faulty result.

Implementation

Future<EventSource> stream(
  Uri url, {
  Map<String, String>? headers,
  String? lastEventId,
  String verb = 'GET',
}) async {
  final request = Request(verb, url);
  if (headers != null) {
    request.headers.addAll(headers);
  }
  request.headers['Accept'] = 'text/event-stream';
  request.headers['Cache-Control'] = 'no-cache';
  if (lastEventId != null) {
    request.headers['Last-Event-ID'] = lastEventId;
  }

  final response = await send(request);
  if (response.statusCode != 200) {
    throw ClientStreamException(await Response.fromStream(response));
  }
  return EventSource(response);
}