Sse.connect constructor

Sse.connect({
  1. required Uri uri,
  2. bool withCredentials = false,
  3. bool closeOnError = true,
  4. Function? reConnect,
  5. List<String>? types,
  6. String eventType = '',
})

Implementation

factory Sse.connect(
    {required Uri uri,
    bool withCredentials = false,
    bool closeOnError = true,
    Function? reConnect,
    List<String>? types,
    String eventType = ''}) {
  final streamController = StreamController<String>();
  final eventSource =
      html.EventSource(uri.toString(), withCredentials: withCredentials);
  if (types != null && types.isNotEmpty) {
    for (var element in types) {
      eventSource.addEventListener(element, (html.Event message) {
        streamController.add((message as html.MessageEvent).data as String);
      });
    }
  } else {
    eventSource.addEventListener(eventType, (html.Event message) {
      streamController.add((message as html.MessageEvent).data as String);
    });
  }

  ///close if the endpoint is not working
  if (closeOnError) {
    eventSource.onError.listen((event) {
      if (eventSource.readyState == 2) {
        eventSource.close();
        streamController.close();
        if (reConnect is Function) {
          reConnect();
        }
      }
    });
  }
  return Sse._internal(eventSource, streamController);
}