public class ServerSentEvents extends Object implements Renderable
renderable
object for streaming server side events.
A renderer
for this type is implicitly provided by Ratpack core.
Example usage:
import org.reactivestreams.Publisher;
import ratpack.http.client.ReceivedResponse;
import ratpack.sse.ServerSentEvents;
import ratpack.test.embed.EmbeddedApp;
import java.time.Duration;
import java.util.Arrays;
import java.util.Objects;
import static ratpack.sse.ServerSentEvents.serverSentEvents;
import static ratpack.stream.Streams.periodically;
import static java.util.stream.Collectors.joining;
import static org.junit.Assert.assertEquals;
public class Example {
public static void main(String[] args) throws Exception {
EmbeddedApp.fromHandler(context -> {
Publisher<String> stream = periodically(context, Duration.ofMillis(5), i ->
i < 5 ? i.toString() : null
);
ServerSentEvents events = serverSentEvents(stream, e ->
e.id(Objects::toString).event("counter").data(i -> "event " + i)
);
context.render(events);
}).test(httpClient -> {
ReceivedResponse response = httpClient.get();
assertEquals("text/event-stream;charset=UTF-8", response.getHeaders().get("Content-Type"));
String expectedOutput = Arrays.asList(0, 1, 2, 3, 4)
.stream()
.map(i -> "event: counter\ndata: event " + i + "\nid: " + i + "\n")
.collect(joining("\n"))
+ "\n";
assertEquals(expectedOutput, response.getBody().getText());
});
}
}
Modifier and Type | Method and Description |
---|---|
org.reactivestreams.Publisher<? extends Event<?>> |
getPublisher()
The stream of events.
|
void |
render(Context context)
Render this object to the response.
|
static <T> ServerSentEvents |
serverSentEvents(org.reactivestreams.Publisher<T> publisher,
Action<? super Event<T>> action)
Creates a new renderable object wrapping the event stream.
|
public static <T> ServerSentEvents serverSentEvents(org.reactivestreams.Publisher<T> publisher, Action<? super Event<T>> action)
Takes a publisher of any type, and an action that mutates a created Event
object for each stream item.
The action is executed for each item in the stream as it is emitted before being sent as a server sent event.
The state of the event object when the action completes will be used as the event.
The action MUST set one of the id
, event
, data
.
T
- the type of object in the event streampublisher
- the event streamaction
- the conversion of stream items to event objectsrenderable
objectpublic org.reactivestreams.Publisher<? extends Event<?>> getPublisher()
public void render(Context context) throws Exception
render
in interface Renderable
context
- the request handling contextException
- any