Skip to main content

sse

Function sse 

Source
pub fn sse<S>(events: S) -> ReplyData
where S: Stream<Item = SseEvent> + Send + Sync + 'static,
Expand description

Build a streaming Server-Sent Events response from a stream of SseEvents. Sets Content-Type: text/event-stream and Cache-Control: no-cache (without which an intermediate cache might hold the live stream, defeating the point).

use actus::prelude::*;
use futures_util::stream;
use std::time::Duration;

pub async fn updates(&self) -> Reply {
    let events = stream::iter(vec![
        SseEvent::data("tick").id("1"),
        SseEvent::data("tick").id("2").retry(Duration::from_secs(5)),
        SseEvent::comment("keep-alive"),
    ]);
    Ok(reply::sse(events))
}

The stream is consumed lazily by the connection — frames are written out as the stream yields, not buffered. When the stream ends, the connection closes.