SseClient constructor

SseClient(
  1. String serverUrl, {
  2. String? debugKey,
})

serverUrl is the URL under which the server is listening for incoming bi-directional SSE connections. debugKey is an optional key that can be used to identify the SSE connection.

Implementation

SseClient(String serverUrl, {String? debugKey})
  : _clientId = debugKey == null
        ? generateId()
        : '$debugKey-${generateId()}' {
  _serverUrl = '$serverUrl?sseClientId=$_clientId';
  _eventSource = EventSource(
    _serverUrl,
    EventSourceInit(withCredentials: true),
  );
  _eventSource.onOpen.first.whenComplete(() {
    _onConnected.complete();
    _outgoingController.stream.listen(
      _onOutgoingMessage,
      onDone: _onOutgoingDone,
    );
  });
  _eventSource.addEventListener('message', _onIncomingMessage.toJS);
  _eventSource.addEventListener('control', _onIncomingControlMessage.toJS);

  _eventSource.onOpen.listen((_) {
    _errorTimer?.cancel();
  });
  _eventSource.onError.listen((error) {
    if (!(_errorTimer?.isActive ?? false)) {
      // By default the SSE client uses keep-alive.
      // Allow for a retry to connect before giving up.
      _errorTimer = Timer(const Duration(seconds: 5), () {
        _closeWithError(error);
      });
    }
  });
}