Module sse

Source
Expand description

Semantic server-sent events (SSE) responder

§Examples

use std::{convert::Infallible, time::Duration};

use actix_web::{Responder, get};
use actix_web_lab::sse;

#[get("/from-channel")]
async fn from_channel() -> impl Responder {
    let (tx, rx) = tokio::sync::mpsc::channel(10);

    // note: sender will typically be spawned or handed off somewhere else
    let _ = tx.send(sse::Event::Comment("my comment".into())).await;
    let _ = tx
        .send(sse::Data::new("my data").event("chat_msg").into())
        .await;

    sse::Sse::from_infallible_receiver(rx).with_retry_duration(Duration::from_secs(10))
}

#[get("/from-stream")]
async fn from_stream() -> impl Responder {
    let event_stream = futures_util::stream::iter([Ok::<_, Infallible>(sse::Event::Data(
        sse::Data::new("foo"),
    ))]);

    sse::Sse::from_stream(event_stream).with_keep_alive(Duration::from_secs(5))
}

Complete usage examples can be found in the examples directory of the source code repo.

Structs§

Data
Server-sent events data message containing a data field and optional id and event fields.
Sse
Server-sent events (text/event-stream) responder.

Enums§

Event
Server-sent events message containing one or more fields.