Package ratpack.sse

Class ServerSentEvents

  • All Implemented Interfaces:

    public class ServerSentEvents
    extends java.lang.Object
    implements Renderable
    A 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;
     import static;
     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 ->
   "counter").data(i -> "event " + i)
         }).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)
             .map(i -> "id: " + i + "\nevent: counter\ndata: event " + i + "\n")
             + "\n";
           assertEquals(expectedOutput, response.getBody().getText());
    See Also:
    Wikipedia - Using server-sent events, MDN - Using server-sent events
    • Method Detail

      • serverSentEvents

        public static <T> ServerSentEvents serverSentEvents​(Publisher<T> publisher,
                                                            Action<? super Event<T>> action)
        Creates a new renderable object wrapping the event stream.

        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 id, event, data or comment.

        Type Parameters:
        T - the type of object in the event stream
        publisher - the event stream
        action - the conversion of stream items to event objects
        a renderable object
      • getPublisher

        public Publisher<? extends Event<?>> getPublisher()
        The stream of events.
        the stream of events
      • render

        public void render​(Context context)
                    throws java.lang.Exception
        Render this object to the response.
        Specified by:
        render in interface Renderable
        context - the request handling context
        java.lang.Exception - any