Skip to main content

Module remote

Module remote 

Source
Expand description

Queries and commands: async data and mutations, as easy to start as tokio::spawn, inspired by SvelteKit’s remote functions and TanStack Query.

A route’s load fetches what its page needs before it is shown. Some data doesn’t belong to a route, though: a badge in a layout, an autocomplete, a count that several pages show. And changing data is often async too (a POST to a backend), which a view can’t await.

  • A Query is async data: it fetches on its first read, and can be refreshed, refetched periodically and cached, so that queries with the same key share one result. A Live makes one from inputs that change.
  • A Command is an async mutation: run it, and see whether it’s pending and how it ended. Once it succeeded, it refreshes the loads and queries that depend on what it changed.

Both are plain values: keep them in the app state, a PageState or any struct of yours. Clones share their state.

§Example

A todo list that fetches the todos from a backend, and adds one with a POST:

use std::sync::{Arc, Mutex};

use egui::Ui;
use egui_kit::remote::{self, Command, Query, QueryState};

/// The backend. A stand-in for an HTTP client like `reqwest::Client`: cheap to clone, and
/// `Send`, as queries and commands run on other threads.
#[derive(Clone, Default)]
struct Api {
    todos: Arc<Mutex<Vec<String>>>,
}

impl Api {
    /// `GET /todos`
    async fn todos(&self) -> Result<Vec<String>, String> {
        Ok(self.todos.lock().unwrap().clone())
    }

    /// `POST /todos`
    async fn add_todo(&self, title: String) -> Result<(), String> {
        if title.is_empty() {
            return Err("a todo needs a title".into());
        }
        self.todos.lock().unwrap().push(title);
        Ok(())
    }
}

struct TodoList {
    api: Api,
    todos: Query<Vec<String>, String>,
    add: Command<(), String>,
    title: String,
}

impl TodoList {
    fn new(api: Api) -> Self {
        // The closure is called for every fetch (the first one, refreshes, refetches), and
        // returns a new future each time, with its own clone of the client.
        let todos = remote::query({
            let api = api.clone();
            move || {
                let api = api.clone();
                async move { api.todos().await }
            }
        })
        // Every query with this key, anywhere in the app, shares this one's value.
        .key("todos")
        // Refetch when "todos" is invalidated, e.g. by the command below.
        .depends("todos");

        Self {
            api,
            todos,
            // Invalidates "todos" once a todo was added.
            add: remote::command().refreshes("todos"),
            title: String::new(),
        }
    }

    fn ui(&mut self, ui: &mut Ui) {
        match self.todos.state() {
            QueryState::Loading => {
                ui.spinner();
            }
            QueryState::Ready(todos) => {
                for todo in todos.iter() {
                    ui.label(todo);
                }
            }
            QueryState::Failed(error) => {
                ui.label(format!("Couldn't load the todos: {error}"));
            }
        }

        ui.horizontal(|ui| {
            ui.text_edit_singleline(&mut self.title);
            if ui.add_enabled(!self.add.is_pending(), egui::Button::new("Add")).clicked() {
                let api = self.api.clone();
                let title = core::mem::take(&mut self.title);
                self.add.run(async move { api.add_todo(title).await });
            }
        });
        if let Some(error) = self.add.error() {
            ui.label(&*error);
        }
    }
}

When the POST succeeds, the command invalidates "todos", the query refetches, and the list shows the new todo. Nothing else has to tell the list that it changed.

§Keys, dependencies and refreshes

They answer different questions:

AnswersSet with
keyWhich data is this? Queries with the same key are the same data.Query::key
dependencyWhen is it outdated? It refetches when one of its dependencies is invalidated.Query::depends, Page::depends
refreshWhat did a mutation change? The dependencies it invalidates when it succeeds.Command::refreshes

A key identifies a query’s value in the cache. Queries with the same key (and value and error types) share one state: they fetch once for all of them, and a query created later finds the value right away, e.g. when a page is opened again. So the key must contain everything the fetch depends on: ("user", id), not "user". A query without a key has a value of its own, which is dropped with it. The key is only hashed, never kept or printed, so it may contain secrets, like the session token of per-user data: ("todos", &token).

A dependency is a name for some data on the backend, like "todos" or "users". It is the same kind of name as a load’s Page::depends: a single invalidation reruns the loads and refetches the queries that depend on it, so many queries can depend on one name, and a query can depend on several. Dependencies are coarser than keys: ("user", 1) and ("user", 2) are two keys that both depend on "users".

A refresh invalidates a dependency once a command succeeded: the command says what it changed, and doesn’t need to know who shows it. Invalidating a dependency directly does the same, with Nav::invalidate in a view, or with invalidate from anywhere on the UI thread.

fn user(api: &Api, id: u32) -> Query<String, String> {
    let api = api.clone();
    remote::query(move || {
        let api = api.clone();
        async move { api.user(id).await }
    })
    .key(("user", id)) // one cache entry per user
    .depends("users") // refetched when any user changes
}

fn rename(api: &Api, rename: &Command<(), String>, id: u32, name: String) {
    let api = api.clone();
    // `rename` was created with `remote::command().refreshes("users")`: once it succeeded,
    // every user query refetches, and so do the loads with `.depends("users")`.
    rename.run(async move { api.rename(id, name).await });
}

The RouterApp applies invalidations at its next frame. A query that is invalidated keeps its value, and refetches the next time it is read.

§Queries from changing inputs

A query is made from its inputs: a date range, a search text, a form to check. A new query fetches on its first read, so a view can’t make one from its current inputs every frame: it would fetch every frame. Keep a Live instead and update it every frame with the inputs: it makes a new query only when they changed. It can also keep showing the previous value while the new one loads, and wait for the inputs to settle (a search being typed) before it asks.

fn week(api: &Api, monday: u32) -> Query<Vec<String>, String> {
    let api = api.clone();
    remote::query(move || {
        let api = api.clone();
        async move { api.week(monday).await }
    })
    .key(("week", monday))
}

fn calendar(
    ui: &mut egui::Ui,
    api: &Api,
    monday: u32,
    appointments: &mut Live<Vec<String>, String>,
) {
    // `appointments` is `remote::live().keep_previous()`: the week before stays until the
    // next one arrives.
    if let Some(list) = appointments.update(monday, || week(api, monday)).data() {
        for appointment in list.iter() {
            ui.label(appointment);
        }
    }
}

§Runtimes

Natively, queries and commands run on a Tokio runtime, so their futures must be Send (see MaybeSend). It is the one the app entered if any (a multi-threaded one, as nothing drives a current-thread runtime between frames), else one that egui-kit starts. RouterApp::ui enters it too, so that hooks and loads can use Tokio-based clients like reqwest. On the web, futures run on the browser’s event loop and needn’t be Send.

A query or command wakes egui up when it finishes, once the app’s context is known on this thread: a RouterApp sets it at each frame, and set_context before the router’s first frame (e.g. for a command that checks a stored session before the router is built) or in an app without a router. Work started earlier wakes egui up too, if the context is known by the time it finishes. Its result is picked up when it is read.

§Caching

A query fetches on its first read, and keeps its value while it refetches. A keyed value outlives its queries for a while, so that a page opened again shows it right away. A query reading a cached value for the first time refetches it if it is older than stale_after, showing the cached value meanwhile.

Dropping a query’s state (its last clone, and its cache entry if keyed) aborts its fetch, like refreshing it aborts the one in progress. Commands always run to completion.

Structs§

Command
An async mutation: run it with a future, and see whether it’s pending and how it ended.
Live
A Query made from inputs that change, like a date range or a search: made again when they do.
Query
Async data: fetches on its first read, then keeps its value until it refetches.

Enums§

QueryState
What a Query has to show.

Traits§

MaybeSend
Send natively, where futures run on the threads of a Tokio runtime, and nothing on the web, where they run on the browser’s event loop.

Functions§

command
A Command.
invalidate
Reruns the loads and queries that depend on key, like Nav::invalidate, from anywhere on the UI thread. The router applies it at its next frame.
live
A Live.
query
A Query that fetches with fetch.
set_context
Sets the app’s context on this thread, so that queries and commands wake it up when they finish, including the ones in progress.