Datastar.SSE (DatastarEx v0.1.0)
View SourceServer-Sent Event (SSE) generator for streaming updates to clients.
This module provides functionality for creating and managing SSE connections, sending events, and handling the streaming lifecycle.
Example
conn
|> put_resp_content_type("text/event-stream")
|> send_chunked(200)
|> Datastar.SSE.new()
|> Datastar.SSE.send_event("my-event", "data content")
Summary
Functions
Marks the SSE connection as closed.
Checks if the SSE connection is closed.
Creates a new SSE generator from a Plug connection.
Sends an SSE event to the client.
Sends an SSE event and raises on error.
Types
@type t() :: %Datastar.SSE{closed: boolean(), conn: Plug.Conn.t()}
Functions
Marks the SSE connection as closed.
Checks if the SSE connection is closed.
@spec new(Plug.Conn.t()) :: t()
Creates a new SSE generator from a Plug connection.
The connection must already have:
- Content type set to "text/event-stream"
- Response status set
- Chunked response initiated via
send_chunked/2
Example
conn
|> put_resp_content_type("text/event-stream")
|> send_chunked(200)
|> Datastar.SSE.new()
@spec send_event(t(), String.t(), [String.t()] | String.t(), keyword()) :: {:ok, t()} | {:error, term()}
Sends an SSE event to the client.
Parameters
sse- The SSE generator structevent_type- The event type (e.g., "datastar-patch-elements")data_lines- A list of data lines or a single stringopts- Optional keyword list with::event_id- Event ID for client tracking:retry- Retry duration in milliseconds
Example
sse
|> send_event("my-event", ["line1", "line2"], event_id: "123", retry: 5000)
Sends an SSE event and raises on error.
Same as send_event/4 but raises if the event cannot be sent.
Returns the updated SSE generator on success.
Example
sse
|> send_event!("my-event", "data")
|> send_event!("another-event", "more data")