Leptos Server Signals

Server signals are leptos kept in sync with the server through websockets.

The signals are read-only on the client side, and can be written to by the server. This is useful if you want real-time updates on the UI controlled by the server.

Changes to a signal are sent through a websocket to the client as diffs, containing only what has been changed, courtesy of the [dipa] crate. The data is encoded using cbor encoding and sent via binary websocket messages.

Feature flags

Example

Cargo.toml

```toml [dependencies] dipa = { version = "", features = ["derive"] } # Used for diffing with serde leptos_server_signal = ""

[features] ssr = [ "leptosserversignal/ssr", "leptosserversignal/axum", # or actix ] ```

Client

```rust use dipa::DiffPatch; use leptos::*; use leptosserversignal::createserversignal;

[derive(Clone, Default, DiffPatch)]

pub struct Count { pub value: i32, }

[component]

pub fn App(cx: Scope) -> impl IntoView { // Provide websocket connection leptosserversignal::provide_websocket(cx, "ws://localhost:3000/ws").unwrap();

// Create server signal
let count = create_server_signal::<Count>(cx);

view! { cx,
    <h1>"Count: " {move || count().value.to_string()}</h1>
}

} ```

Server (Axum)

```rust

[cfg(feature = "ssr")]

pub async fn websocket(ws: WebSocketUpgrade) -> axum::response::Response { ws.onupgrade(handlesocket) }

[cfg(feature = "ssr")]

async fn handle_socket(socket: WebSocket) { let websocket = Arc::new(Mutex::new(socket)); let mut count = ServerSignal::::new(websocket);

loop {
    tokio::time::sleep(Duration::from_millis(10)).await;
    if count.with(|count| count.value += 1).await.is_err() {
        break;
    }
}

} ```