
# Server-sent events

Server-sent events (`text/event-stream`) let a server push a series of messages over one long HTTP response: notifications, progress, live prices. The type for such a stream is `EventStream<T>`. It **is** a `Stream<T>` of the events' data, so the usual case needs no wrapper type; `.events` gives the whole events (`ServerSentEvent<T>`) when the id or name matters.

## Why

A stream of events should read like a stream of values, and reconnect by itself after a network drop, as a browser's `EventSource` does. The same type serves a Feign client that reads events and a controller that writes them.

## Example

```dart
@FeignClient('orders', url: r'${orders.url}')
abstract interface class OrdersClient {
  @GetMapping('/orders/events')
  EventStream<OrderEvent> events();
}

// Only the data: each event's JSON read as an OrderEvent.
await for (final order in orders.events()) {
  log.info(order.status);
}

// The whole events, when the event name tells the kinds apart.
orders.events().events.listen((e) => log.info('${e.id} ${e.event} ${e.data}'));
```

On a server, a `@RestController` method can return an `EventStream<T>`; the web starter writes the events as the response (see [Server-sent events in the web starter](../spring-boot-starter-web/streaming/sse.md)).

## The types

| Type | What |
|---|---|
| `EventStream<T>` | A cold `Stream<T>` of the events' data: nothing happens until someone listens, each listener opens its own connection, and cancelling (or `break` in `await for`) closes it. `.events` gives the whole events. |
| `EventStream.fromIterable`, `EventStream.of`, `EventStream.fromEvents` | Build one, for fallbacks and tests. |
| `ServerSentEvent<T>` | One event: `data`, `id`, `event`, `retry`, `comment`. |
| `connectServerSentEvents(connect, reconnect:, onReconnect:)` | Opens the connection on any `HttpTransport` and reconnects as `EventSource` does. |
| `SseReconnect(enabled:, delay:, maxAttempts:, retryIf:)` | The rules: wait `delay` (3 seconds by default), or the server's `retry:`, and send `Last-Event-ID` so the server can resume. A `204 No Content` stops the stream. `SseReconnect.never` does not reconnect. |
| `SseDecoder` | Parses a `text/event-stream` body following the HTML specification. |

## By hand

```dart
// `transport` is the application's HttpTransport bean.
Stream<ServerSentEvent<String>> orderEvents() =>
    connectServerSentEvents((lastEventId) async {
      final response = await transport.stream(HttpRequest(
        method: HttpMethod.get,
        url: Uri.parse('https://api.neon.books/orders/events'),
        headers: HttpHeaders({
          'Accept': MediaType.textEventStream,
          // Resume after the last event seen before the drop.
          if (lastEventId != null) 'Last-Event-ID': lastEventId,
        }),
      ));
      if (!response.isSuccess) {
        // Not a network failure: the stream ends with this error.
        throw StateError((await response.read()).bodyText);
      }
      return response;
    });

// Each listener of `orders` opens its own connection.
final orders = EventStream<String>(orderEvents);
```

## In Spring (Java)

```java
Flux<ServerSentEvent<OrderEvent>> events = webClient.get().uri("/orders/events")
    .retrieve().bodyToFlux(new ParameterizedTypeReference<>() {});
```

Spring has no `EventStream`: `WebClient` and `@HttpExchange` interfaces return `Flux<ServerSentEvent<T>>` (or `Flux<T>`), and Spring Cloud OpenFeign cannot stream at all. Here the event wrapper is folded into the stream type, and reconnection is built in (in Spring it is `Flux.retryWhen`).

## See also

- [HTTP transport](http-transport.md)
- [Server-sent events in Feign](../spring-boot-starter-feign/server-sent-events.md)
- [Testing](testing.md)
