Skip to main content

SseHandler

Trait SseHandler 

Source
pub trait SseHandler:
    Send
    + Sync
    + Sized
    + 'static {
    type Event: Eventable;
    type EventStream: Stream<Item = Self::Event> + Unpin + Send + 'static;

    // Required method
    fn connect(
        &self,
        conn: &mut Conn,
    ) -> impl Future<Output = Self::EventStream> + Send;
}
Expand description

The trait that defines an event source for the Sse handler.

Implement this on a type that holds whatever fanout mechanism your application uses — a broadcast channel, a subscription registry — and return a per-client Stream from connect.

use broadcaster::BroadcastChannel;
use trillium::Conn;
use trillium_sse::{Sse, SseHandler};

struct Notifications {
    channel: BroadcastChannel<String>,
}

impl SseHandler for Notifications {
    type Event = String;
    type EventStream = BroadcastChannel<String>;

    async fn connect(&self, _conn: &mut Conn) -> Self::EventStream {
        self.channel.clone()
    }
}

let handler = Sse::new(Notifications {
    channel: BroadcastChannel::new(),
});

This trait is also implemented for any Fn(&mut Conn) -> Stream, for the common case where nothing needs to be awaited in order to build the stream:

use futures_lite::stream;
use trillium::Conn;
use trillium_sse::sse;

let handler = sse(|_: &mut Conn| stream::iter(["one", "two"]));

Required Associated Types§

Source

type Event: Eventable

The type yielded by this handler’s EventStream.

Source

type EventStream: Stream<Item = Self::Event> + Unpin + Send + 'static

A Stream of events to send to a connected client, built per client in connect.

Required Methods§

Source

fn connect( &self, conn: &mut Conn, ) -> impl Future<Output = Self::EventStream> + Send

Called once per request, to build the stream of events for that client.

Returning None leaves the conn untouched, so it continues on to subsequent handlers. The conn is borrowed mutably to allow setting response headers or state, but note that Sse sets the status, headers, and body itself when a stream is returned.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl<F, S, E> SseHandler for F
where F: Fn(&mut Conn) -> S + Send + Sync + 'static, S: Stream<Item = E> + Unpin + Send + 'static, E: Eventable,