Skip to main content

Crate eventful_rs

Crate eventful_rs 

Source
Expand description

§eventful-rs

This guide shows how to use eventful-rs to have struct values talk to each other across different threads (shards), either by calling their methods via a dispatcher, or through events. Either experiment on your own, or follow the tutorial to build a small product importer with progress display.

§Quick start

Create a Rust project (or use an existing one):

cargo new product-import
cd product-import

Add eventful-rs under [dependencies] in Cargo.toml:

[dependencies]
eventful-rs = "0.2"

No features are required: the built-in thread runtimes can run async methods. If your code needs Tokio’s timers or I/O, see when you need another runtime.

§Tutorial: import products and display progress

We’ll build a small command-line application that imports a list of products. The importer will clean up product names, skip empty entries, and report each accepted product to a display. Importing runs on a worker thread; the display handles progress on the main thread, as it would in a UI application.

The importer should know how to process products without knowing anything about the display. We’ll give it a progress event and connect a listener to that event. Calling the importer through a handle will run its method on the worker; eventful-rs will deliver each progress update on the display’s thread.

By the end, we’ll be able to start an import, display its progress, and wait for both the work and its updates to finish. The work itself is deliberately small so we can focus on how the pieces communicate. First we’ll walk through those pieces, then put them together in a complete program.

§1. Choose where the work runs

A shard is an event loop and the values it owns on one thread. We’ll use two: one on the main thread for displaying progress, and one on a background thread for importing products.

use eventful_rs::*;

declare_shard!(pub Main, runtime = main);
declare_shard!(pub Worker, runtime = std);

These declarations give us names we can use when assigning a struct to a thread. The worker starts when first used. Later, #[sharded_main(Main)] will drive the main thread’s event loop while our application waits for the import to finish.

§2. Give the importer a progress event

An event describes what happened. Define it as a trait with #[events]:

use eventful_rs::*;

#[events]
trait ImportEvents {
    fn imported(&self, name: String);
}

A listener implements this trait to decide what to do with each product name. The importer doesn’t need to know which listeners are connected.

In the complete program, #[eventful(ImportEvents, shard = Worker)] attaches these events to Importer and assigns it to the worker. Its Cell<usize> counts products across calls. That state stays on the worker; no mutex is needed to access it there.

§3. Make the import callable from the main thread

Write the import logic as an ordinary method. #[asynchronize] on the impl and #[asynced] on the method also make it callable through the importer’s handle:

let count = importer.import(rows).await?;

Here importer is a handle, not a reference to the worker’s object. The call sends rows to the worker, runs the method there, and brings its result back. While the main thread awaits that result, its event loop can handle progress updates.

For each accepted row, our method calls self.events.imported().tracked().emit(name).await?. The events field exposes emission builders for the declared event interface. It delivers the event to connected listeners and waits for their handlers to finish. This lets our final “Done” message mean that all progress has been displayed too.

§4. Connect a display and run the application

Progress lives on Main and implements ImportEvents by printing each product name. We create both objects with spawn, which runs a constructor on the object’s chosen thread and returns a handle.

Then we connect them:

let _subscription = importer.imported().connect(&progress).scoped();

The connection delivers imported events to progress on the main thread. Keeping the scoped subscription in a variable keeps the connection active; dropping it disconnects the listener. Keep the progress handle alive too: a connection does not own its listener.

§The complete program

use eventful_rs::*;
use std::cell::Cell;

declare_shard!(pub Main, runtime = main);
declare_shard!(pub Worker, runtime = std);

#[events]
trait ImportEvents {
    fn imported(&self, name: String);
}

#[eventful(ImportEvents, shard = Worker)]
struct Importer {
    total: Cell<usize>,
}

#[asynchronize]
impl Importer {
    #[asynced]
    async fn import(&self, rows: Vec<String>) -> Result<usize, DeliveryError> {
        let mut count = 0;
        for row in rows {
            let name = row.trim();
            if name.is_empty() {
                continue;
            }
            self.total.set(self.total.get() + 1);
            self.events.imported().tracked().emit(name.to_owned()).await?;
            count += 1;
        }
        Ok(count)
    }

    #[asynced]
    fn total(&self) -> usize {
        self.total.get()
    }
}

#[eventful(shard = Main)]
struct Progress;

impl ImportEvents for Progress {
    fn imported(&self, name: String) {
        println!("Imported: {name}");
    }
}

#[sharded_main(Main)]
async fn main() -> Result<(), DeliveryError> {
    let importer = Importer::spawn(|| Importer {
        total: Cell::new(0),
        events: Default::default(),
    }).await?;
    let progress = Progress::spawn(|| Progress {
        events: Default::default(),
    }).await?;

    let _subscription = importer.imported().connect(&progress).scoped();
    let count = importer.import(vec![" Apples ".into(), "".into(), "Pears".into()]).await?;
    println!("Done: {count} products imported");
    assert_eq!(importer.total().await, 2);
    Ok(())
}

Run it with cargo run:

Imported: Apples
Imported: Pears
Done: 2 products imported

The events: Default::default() fields initialize the event storage added by #[eventful], including on listeners. #[sharded_main] runs the main event loop and joins background shards after main returns.

Notice that total is a synchronous method on Importer, but calling it through the handle is asynchronous: even reading the counter has to happen on its owning thread. You can add another import call and the counter will retain its value.

You now have a worker with its own state, a main-thread listener, and a connection between them. To add another consumer, implement ImportEvents on another #[eventful] type, create it, and connect it to the same signal. The importer needs no changes.

§Using this in your project

Start by deciding which values need to share a thread. Several types can use the same shard; you don’t need a thread per object. Assign each with #[eventful(shard = Worker)], adding its event trait if it produces events. For a module of related types, sharded can set their shard together.

Use spawn to construct values where they belong. Its closure can build Rc, Cell, and RefCell state on that thread. Captures sent into the closure must be Send, but the constructed value doesn’t have to be. The returned ShardRcHandle can be cloned and passed to other threads.

Mark methods you want to call through handles with #[asynced]. When splitting code into modules, use #[asynchronize(pub)] and import the generated extension trait at the call site. If a command needs no result, #[action] queues it immediately, including from synchronous code.

Use events when other parts of the application need to react to a change. self.events.imported().emit(name) queues progress without waiting for listeners; self.events.imported().tracked().emit(name).await? waits for their handlers. In our example, waiting for each update keeps the producer paced by the display. A delivery failure returns a DeliveryError; it does not undo the counter change or any handler that already ran.

A few rules matter as your application grows:

  • Keep handles and subscriptions alive. A strong handle keeps a value alive while its shard runs. Connections hold listeners weakly. Use .scoped() for cleanup on drop; a plain Connection stays connected until disconnected.
  • Allow for async interleaving. A shard starts queued calls in order, but other calls may run when an async method awaits. Don’t keep a RefCell borrow across an await if another call might access it.
  • Limit outstanding work. Queues are unbounded. Awaiting each call or tracked event is one way to avoid submitting work faster than it can be handled.
  • Finish workflows before shutting down. Complete the calls and deliveries your application needs before returning from main. For manual lifecycle management, see EventLoop and join_all_shards.

A panic in a callback, dispatched method, or local task does not stop its shard. The driver isolates it and prints eventful-rs: shard callback panicked to stderr. Applications that own the terminal, such as TUIs, can send these reports elsewhere with set_panic_reporter. The standard panic hook still runs where the panic happened; replace it with std::panic::set_hook if it also writes to the terminal.

use eventful_rs::*;
set_panic_reporter(|panic| {
    // Write to a log file or an in-app log view instead.
    let _ = (panic.shard_id(), panic.message());
});

§When you need another runtime

The example uses std for a background thread and main for the calling thread. They can run async methods, but don’t provide Tokio’s timers or I/O reactor. If your worker uses Tokio-based networking or timers, enable the adapter:

[dependencies]
eventful-rs = { version = "0.2", features = ["tokio"] }

Then select runtime = tokio for that worker. Use runtime = tokio_main if the main thread also needs Tokio. Tokio is optional and disabled by default.

For a Slint application, enable slint and use runtime = slint to deliver callbacks through the UI loop. The application selects its Slint backend and renderer. Initialize the shard on the UI thread, and await shutdown_async() before quitting the UI loop. See the slint_rt module for integration details.

§Local values and UI callbacks

Self::spawn(factory) queues construction and returns a future yielding a strong remote handle. Self::bind_local(value) binds immediately on the named shard’s thread and returns Result<ShardRc<Self>, InvokeError>. It keeps the usual explicit struct initialization, including events: Default::default().

Connect a local source with source.connect_to(&receiver). The direction is always source to receiver; the source must declare outgoing events. The receiver only needs to implement their handlers. On a local ShardRc, the source value owns these subscriptions and removes them when it is destroyed. ShardRc::connect(&source, &receiver) is the same operation as an associated function, so it never conflicts with a connect method on the wrapped value.

Use ShardRc::downgrade(&window) for a local weak reference and .upgrade() to recover an optional local strong reference synchronously. These references cannot cross threads; use a ShardWeakHandle for queued access from other threads. The shard collects a value soon after its last strong reference is released and any in-flight callbacks on it finish, so weak upgrades can succeed until then. A local strong reference can also keep a value alive after shard shutdown; upgrading it does not restart event delivery.

Code already running on a value’s shard can turn a handle back into a local reference with handle.try_local(), without queuing a job. This is useful when values on one shard share a local service, such as an HTTP client with generic methods that have no handle wrapper:

use eventful_rs::*;
declare_shard!(Net, runtime = main);

#[eventful(shard = Net)]
struct Client;
impl Client {
    fn request<T: Default>(&self, _path: &str) -> T { T::default() }
}

#[eventful(shard = Net)]
struct Rooms {
    client: ShardRc<Client>,
}

Net::shard().run_main(|| async {
    let client = Client::bind_local(Client { events: Default::default() })?.to_handle();
    // For example inside a spawn factory or a dispatched method on the shard:
    let rooms = Rooms::bind_local(Rooms {
        client: client.try_local()?,
        events: Default::default(),
    })?;
    let count: u32 = rooms.client.request("/rooms");
    assert_eq!(count, 0);
    Ok::<(), InvokeError>(())
})?;

ShardRcHandle::try_local fails with WrongShard on any other thread, so the reference still never leaves its shard. ShardWeakHandle::try_local returns Ok(None) once the value has been collected.

Some values live as long as the application, such as a main window or a shared service, and have no natural owner to hold their reference. ShardRc::detach(value) hands the value to its shard and returns a ShardWeakHandle for reaching it; handle.detach() does the same from any thread. The shard keeps detached values alive until it shuts down. Then, after queued work has drained, it destroys them on its own thread in reverse detach order, so a service detached after the client it uses is destroyed first. To release a value earlier, keep a strong handle instead of detaching it.

For callbacks owned by the UI, capture a weak reference instead of cloning the window into its own callback:

use eventful_rs::*;
use std::cell::Cell;
declare_shard!(Ui, runtime = main);

#[eventful(shard = Ui)]
struct Window {
    edits: Cell<u32>,
}
impl Window {
    fn edit_paragraph(&self, _id: u32) {
        self.edits.set(self.edits.get() + 1);
    }
}

Ui::shard().run_main(|| async {
    let window = Window::bind_local(Window {
        edits: Cell::new(0),
        events: Default::default(),
    })?;
    // In a UI application, pass these closures to the component's `on_*` setters.
    let edit = window.weak_callback(|window, id| window.edit_paragraph(id));
    let edits = window.weak_callback_or_else(|window, ()| window.edits.get(), |()| 0);

    edit(7);
    assert_eq!(edits(()), 1);
    Ok::<(), InvokeError>(())
})?;

weak_callback skips calls once the value is destroyed. It takes one argument; use () for zero arguments or a tuple adapter for multiple arguments. These callbacks run synchronously on the calling thread without queuing. For callbacks returning a value, weak_callback_or_else(handler, fallback) requires an explicit fallback closure receiving the same argument. Avoid capturing a strong reference to the owner inside either closure, which would reintroduce the cycle.

§Background work on a shard

Worker::spawn_local(future) (ShardBinding::spawn_local) runs a future on a declared shard’s own thread, and ShardRc::spawn_local(&value, future) on a value’s shard. Call them from code already running there. The future need not be Send, so it can hold Rc, RefCell, or a ShardRc. The shard’s driver polls it on a later turn, and it interleaves with queued calls at each .await. This works on every runtime; a future that uses Tokio timers or I/O still needs a Tokio shard.

Every task has an owner. Dropping the returned LocalTask aborts the task at its next .await; detach() lets it run and returns a cloneable TaskHandle that can still abort it. Awaiting a LocalTask from another future on the same shard yields the task’s output, or InvokeError::Canceled if it was aborted and InvokeError::Panicked if it panicked. Shutdown aborts all local tasks before draining queued work, so a polling loop never holds up shutdown. For a loop that belongs to a value, use ShardRc::spawn_owned: the task is aborted when the value is destroyed and receives a weak reference, so it does not keep the value alive.

use eventful_rs::*;
use std::cell::Cell;
declare_shard!(Net, runtime = main);

#[eventful(shard = Net)]
struct ChatFeed {
    polls: Cell<u32>,
}
async fn next_batch() { /* await a long-polling request here */ }

Net::shard().run_main(|| async {
    let feed = ChatFeed::bind_local(ChatFeed { polls: Cell::new(0), events: Default::default() })?;
    let task = ShardRc::spawn_owned(&feed, |feed| async move {
        loop {
            next_batch().await;
            // Upgrade per iteration; a strong reference across `.await` keeps
            // the value alive for as long as the loop runs.
            let Some(feed) = feed.upgrade() else { return };
            feed.polls.set(feed.polls.get() + 1);
        }
    })?;
    // Dropping the last reference to the feed also stops its loop.
    Ok::<(), InvokeError>(())
})?;

A task that captures a strong reference keeps that value alive until the task ends; prefer spawn_owned or a ShardWeak. Panics in a task are reported like callback panics and mark it finished; the shard keeps running. Running Tokio’s own spawn_local on Tokio shards happens to work today, but it is not guaranteed and its tasks are invisible to shutdown.

§Bridging Slint callbacks

Use #[slint_events(component = ComponentType)] on an explicit callback interface. It generates the usual event traits and a <TraitName>Bridge source. Callback names map to Slint setters: edit_paragraph installs on_edit_paragraph.

use eventful_rs::*;
slint::slint! {
    export component EditorUi inherits Window {
        callback save();
        callback edit-paragraph(string);
    }
}
declare_shard!(UiShard, runtime = slint);

#[slint_events(component = EditorUi)]
trait UiActions {
    fn save(&self);
    fn edit_paragraph(&self, id: slint::SharedString);
}

#[eventful(shard = UiShard)]
struct Editor {
    ui: EditorUi,
    ui_events: UiActionsBridge,
}
impl UiActions for Editor {
    fn save(&self) { /* save the document */ }
    fn edit_paragraph(&self, id: slint::SharedString) { /* open the editor */ }
}

let ui = EditorUi::new()?;
let ui_events = UiActionsBridge::new(&ui);
let editor = Editor::bind_local(Editor {
    ui, ui_events, events: Default::default(),
})?;
editor.ui_events.connect_to(&editor);
// Retain editor in your application and run the Slint event loop.

The bridge is local to the UI thread and retains no component or receiver. Store it in the wrapper so it lives as long as the wrapper, and keep the wrapper’s ShardRc alive for as long as the window is open. It is the only strong owner, while Slint keeps a shown window alive on its own: dropping the ShardRc, for example at the end of a setup function, leaves the window on screen but silently stops delivering its callbacks. For a window that lives as long as the application, ShardRc::detach(editor) hands it to the shard. Slint callbacks hold only a weak reference to the bridge; dropping the bridge stops forwarding even if something else retains its event storage. Already queued events can still run.

Installation replaces the handlers for the listed callbacks. Later on_* registrations replace the bridge’s handlers in turn. Dropping a bridge does not clear or restore handlers, so it cannot accidentally remove a newer registration. Unlisted callbacks are unaffected.

Delivery is queued, including delivery to a wrapper on the same UI shard. Handlers run after the original Slint callback returns. For async work, a handler can queue an existing asynchronous handle method or start a local task.

Callback argument types must match Slint’s generated signatures and implement Clone + Send + 'static, just like ordinary event payloads. For example, use slint::SharedString for a Slint string and convert it in the receiver if needed. Payload conversion and local-only payloads require manual callback wiring for now. Callbacks with return values and labelled events are not supported by this bridge; callbacks needing an immediate result must remain synchronous handlers.

Individual signal connections, receiver callbacks, and role selection are also available through the generated subscription API. A bridge with no enabled callbacks cannot be bulk-connected. Conditional callback declarations propagate to the registrations as well as the event interface.

§Distinguishing sources and connecting methods

#[events] adds a defaulted role parameter to the listener trait. The producer and its event storage do not need a role. Select the receiver implementation when making a connection:

use eventful_rs::*;
#[events]
trait PushButtonEvents {
    fn on_clicked(&self);
}
struct ButtonA;
struct ButtonB;
#[eventful(PushButtonEvents, shard = DynamicShard)]
struct PushButton;
#[eventful(shard = DynamicShard)]
struct Dialog;
impl PushButtonEvents<ButtonA> for Dialog {
    fn on_clicked(&self) { self.pressed_a(); }
}
impl PushButtonEvents<ButtonB> for Dialog {
    fn on_clicked(&self) { self.pressed_b(); }
}
impl Dialog {
    fn pressed_a(&self) {}
    fn pressed_b(&self) {}
}
fn wire(a: &ShardRcHandle<PushButton>, b: &ShardRcHandle<PushButton>, dialog: &ShardRcHandle<Dialog>) {
    a.on_clicked().role::<ButtonA>().connect(dialog);
    b.on_clicked().role::<ButtonB>().connect(dialog);
}

impl PushButtonEvents for Dialog and ordinary .connect(dialog) select the role (). Named roles need no values or marker traits. They describe the role of a connection, not an intrinsic identity of the button.

Event methods may have a default body, such as fn on_hovered(&self) {}, so a listener implements only the events it needs; with roles, each role impl gets its own defaults. Bulk connections still deliver every event, and a delivery to a handler the listener did not override runs the default. For very frequent events, connect only the signals the listener handles.

For all events in an interface, use source.role::<ButtonA>().connect(dialog) on a strong handle, or source.events().role::<ButtonA>().connect(dialog). Weak handles return None if their event storage has expired. ShardRc::role::<ButtonA>(&local_source).connect(dialog) additionally ties the subscriptions to the source value’s lifetime, just like ShardRc::connect.

To connect a method directly, use a.on_clicked().with_receiver(dialog).connect(Dialog::pressed_a). A capturing closure works as well: a.on_clicked().with_receiver(dialog).connect(move |d| d.pressed_a()). Callbacks receive &Dialog followed by the event arguments and return (). They need no event-interface implementation, but still satisfy any extra receiver bound declared with #[events(ExtraTrait)].

Callback captures must be Send + Sync + 'static; the receiver may contain Rc, Cell, or RefCell, since callbacks run on its own shard. The connection holds the receiver weakly. Explicitly capturing a strong handle in a closure retains that handle in the usual way.

Labelled signals support .labelled(label).role::<ButtonA>().connect(dialog) and .labelled(label).with_receiver(dialog).connect(callback). Labels filter emissions; roles select the receiver implementation. Unlabelled connections to labelled signals receive every emission.

All these methods return the existing connection tokens or groups. Dropping a plain token leaves the subscription active; use disconnect() or retain a scoped() guard for cleanup. Tracked emission waits for selected callbacks to finish and reports dispatch failures or panics.

§Emission and subscription builders

The private events field on an eventful source owns emission access. Emit from source methods with self.events.changed().emit(value); add .tracked() to observe completion and .labelled(label) for labelled events. A labelled emission must select a label. Label and tracking selection can appear in either order. Emission submits immediately; dropping its completion future does not cancel delivery, and the future does not borrow the source.

Remote handles and HasEvents::events() expose subscription-only views. To request an emission remotely, call a source action or dispatch onto the source. For standalone callbacks, select a shard with .on_shard(...) instead of a receiver:

use eventful_rs::*;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

declare_shard!(Main, runtime = main);
declare_shard!(Worker, runtime = std);

#[events]
trait CounterEvents {
    fn changed(&self, value: u32);
}

#[eventful(CounterEvents, shard = Worker)]
struct Counter;

#[sharded_main(Main)]
async fn main() -> Result<(), DeliveryError> {
    let counter = Counter::spawn(|| Counter { events: Default::default() }).await?;

    // Runs on `Main`, including when the emitter is already on `Main`.
    let seen = Arc::new(AtomicU32::new(0));
    let observer = seen.clone();
    let _callback = counter
        .changed()
        .on_shard(&Main::handle())
        .connect(move |value| observer.store(value, Ordering::Relaxed))
        .scoped();

    // `events` is private to the source, so emit from the source's shard.
    let value = 7;
    counter
        .deferred_upgrade_in_shard(async move |counter| {
            counter.events.changed().tracked().emit(value).await
        })
        .await?;
    assert_eq!(seen.load(Ordering::Relaxed), 7);
    Ok(())
}

For a labelled signal, .labelled(topic) composes before or after .on_shard(...). Captures require Send + Sync + 'static. There is no weak receiver to expire; captures remain registered until disconnected or their subscription storage is released. Use .scoped() on the returned connection for automatic cleanup. The event interface’s extra receiver bounds apply to receiver connections, not to standalone callbacks. Callbacks return (); independently spawned work is not included in tracked completion.

A source can subscribe to its own events through self.events.changed().signal().connect(&receiver). This conversion preserves an already selected label. Subscription access cannot be converted back into emission access. Weak handles expose events() -> Option<Arc<EventSet>>; upgrade that view before choosing a signal. Retaining a subscription view does not keep the source value alive.

Generated implementation details live in a private module. Declare #[events] interfaces at module scope, including inside inline modules, so their payloads, labels, and receiver bounds can be resolved from that module. Public types and signal extension traits are re-exported with the interface’s visibility. There is no generated emitter extension trait. The low-level Event type remains available for applications explicitly owning raw event storage.

§Building custom event sources

The type of the events field is part of the public API: for an interface Keys, #[events] generates KeysEmissions with the interface’s visibility. It implements Default, has one emission builder per event (emissions.pressed().emit(key)), and signals() returns its subscription view, &Arc<KeysEventSet>. Any type that owns a KeysEmissions can act as an event source by implementing HasEvents<KeysEventSet> with signals() and adding the KeysSignalsExt signal accessors. This is how the Slint bridge and input adapters for other UI libraries forward external callbacks into typed events:

use eventful_rs::*;
use std::sync::Arc;

mod keys {
    #[eventful_rs::events]
    pub trait Keys {
        fn pressed(&self, key: char);
    }
}
use keys::{KeysEmissions, KeysEventSet, KeysSignalsExt};

#[derive(Default)]
struct KeyBridge {
    events: KeysEmissions,
}
impl KeyBridge {
    /// Report synchronously whether a key was bound; delivery is queued.
    fn dispatch(&self, key: char) -> bool {
        self.events.pressed().emit(key);
        true
    }
}
impl HasEvents<KeysEventSet> for KeyBridge {
    fn events(&self) -> &Arc<KeysEventSet> {
        self.events.signals()
    }
}
impl KeysSignalsExt for KeyBridge {}

Receivers connect with bridge.pressed().connect(&receiver) or, for every event, bridge.events().role::<()>().connect(&receiver). Keep emission access private to the adapter, just like the events field of an eventful source.

§Where to go next

The runnable examples build on these ideas:

  • sharded-main expands the importer into modules and adds actions and access to multiple values in one call.
  • no-main-shard-example integrates workers into a synchronous application.
  • connect-all connects an entire event interface and manages subscriptions.
  • targeted-events routes notifications by topic using EventLabel.
  • example_tokio performs HTTP I/O on a worker and reports to the main thread.

For more control, see ShardRcHandle::join for accessing several values on one shard, DynamicShard for selecting a shard at runtime, and DeliveryError for tracked delivery outcomes.

§Glossary

ConceptMeaning
ShardAn event loop and the values it owns on one thread. Several objects can share a shard.
Event loopRuns queued calls and event handlers on the shard’s thread, and polls their async work.
Shard affinityThe choice of shard for a type, such as shard = Worker. It determines where its values are created and their methods run.
Eventful valueAn object managed by a shard, usually declared with #[eventful]. It can produce events, listen to them, or simply expose methods.
HandleA way to communicate with an object on its shard without accessing the object directly. A strong ShardRcHandle can cross threads and keeps the object alive while the shard runs; a weak handle does not keep it alive.
Event interfaceA trait declared with #[events]. Its methods describe the notifications a producer can emit and a listener can handle.
SignalOne event on a particular producer, such as importer.imported(). Connect listeners to it to receive that notification.
ListenerAn eventful value that implements an event interface. Its handlers run on its own shard.
ConnectionA subscription linking a producer’s signal to a listener. It holds the listener weakly, so the listener also needs a live strong handle.
Scoped subscriptionA connection wrapped with .scoped() so dropping it disconnects the listener. Dropping a plain connection does not disconnect it.
Tracked emissionAn event emission that returns a future for the selected handlers’ outcomes. Awaiting it waits for those handlers, but not for work they independently spawn.
Async method dispatchCalling a method through a handle with #[asynced]. Polling the call queues it on the object’s shard; awaiting it obtains the method’s result.
ActionA method marked #[action] that a handle queues immediately without waiting for a result. The method must return ().
Runtime backendThe implementation that drives a shard, such as the standard thread runtime, Tokio, or Slint’s UI loop.

Modules§

local_rt
Calling-thread shard using executor-independent Rust futures.
slint_rt
Slint UI-thread adapter. Construct and bind on the UI thread; keep its event loop running while work is pending. Request shutdown before quitting Slint.
std_rt
Dedicated-thread shard using executor-independent Rust futures.
task
Detached blocking work with cooperative cancellation. Callbacks run on the worker thread; use shard handles to update eventful values.
tokio_local_rt
Calling-thread shard using Tokio.
tokio_rt
Dedicated-thread shard using Tokio.

Macros§

declare_shard
Declare a named singleton: declare_shard!(pub Worker, runtime = std);.
use_shard
Select the default shard for eventful types in the current module/file.

Structs§

CallbackPanic
A shard callback, job, or local task panicked. The driver isolated the panic and the shard keeps running. Mutations made before the panic are not rolled back.
Connection
A Connection instance represents a connection between an event and a listener. It can be used to disconnect the listener from the event. Dropping a Connection instance will not automatically disconnect the listener, you may use the scoped method to create a ScopedConnection if this is desired. Label is the signal routing type; it defaults to () for unlabelled events. See the crate::Event example for registration and cleanup.
ConnectionGroup
Connections for all signals of one event interface. Dropping the group keeps subscriptions active. Call disconnect() or use scoped() to disconnect every subscription. Groups created by ShardRc::connect also disconnect when their owning value is destroyed. Targets remain weak. See the crate::Event example for collection and scoped cleanup.
Event
Type-erased connection storage for one signal signature and optional label type.
JoinedHandles
Strong handles validated to belong to the same shard.
LocalTask
Owning guard for a task running on a shard’s thread. Dropping it aborts the task, like dropping a crate::ScopedConnection disconnects. Use Self::detach to let the task run on its own.
RoleConnections
Receiver-role adapter for a whole source interface.
ScopedConnection
A ScopedConnection instance represents a connection between an event and a listener. It can be used to disconnect the listener from the event. Dropping a ScopedConnection instance will automatically disconnect the listener from the event. See the crate::Event example for scoped cleanup.
ScopedConnectionGroup
A group that disconnects on drop. Dropping any clone disconnects the group, matching ScopedConnection semantics. See the crate::Event example.
ShardEventHandle
Thread-safe submission handle shared by the runtime backends. Submitted closures cross threads; shard-local values and their callback futures do not.
ShardId
Opaque process-local shard identity, allocated by ShardId::new.
ShardRc
Strong reference to a shard-local value. This reference cannot cross threads. See the crate::DynamicShard construction example. Dereferences to the value; use Sharded::to_handle for remote access.
ShardRcHandle
Strong thread-safe handle retaining a shard-local value while its shard runs. See the quick start and Self::join example. Shutdown destroys the store even when handles remain alive.
ShardWeak
Weak shard-local reference. It is neither Send nor Sync and does not keep the value alive. Values remain upgradeable until the shard collects them. The shard collects a value soon after its last strong reference is released and in-flight callbacks finish. A surviving local strong reference also permits upgrades after shard shutdown.
ShardWeakHandle
Thread-safe handle that does not retain its target or event storage. See the calling methods guide. Untracked calls skip expired targets; tracked calls report delivery failures.
TaskHandle
Non-owning, cloneable control handle for a local task. It can be used from any thread; dropping it does not affect the task.

Enums§

DynamicShard
Explicit opt-in to selecting a shard at runtime with bind/bind_async. Such a value’s actual destination is carried by its handle, not its type.
InvokeError
A submission or deferred invocation failed.
ShardError
Failure to join a shard or post work to a backend.

Traits§

ConnectEvents
Implemented by generated event sets for compatible listener types.
ConnectEventsAs
Implemented by event sets that support a connection-selected receiver role. Role values are never stored or sent between shards.
EventLabel
Routing metadata for a labelled event.
EventLoop
Lifecycle and construction interface shared by runtime backends. See the crate::DynamicShard construction example.
EventLoopHandle
Thread-safe submission contract implemented by shard backends. See the calling methods guide. Built-in backends queue accepted jobs in admission order; async jobs may interleave.
Eventful
Event interface and shard affinity for a type.
HasEvents
Access subscription-only event storage generated by crate::eventful. Emission access belongs to the source’s private events field.
ShardAffinity
Affinity used to validate binding through a runtime shard handle. Named bindings return one stable shard ID. DynamicShard accepts any shard.
ShardBinding
A named singleton shard. Implementations must always return the same shard. Prefer declare_shard! to implementing this trait manually.
ShardHandle
Dispatch work to a shard-local value through a thread-safe handle. See the calling methods guide.
Sharded
Obtain a dispatch handle from a local reference or remote handle. See the crate::DynamicShard construction example.

Functions§

join_all_shards
Stop and join registered background shards without holding the registry lock. Call from synchronous code, after producers have finished submitting work.
join_all_shards_async
Join background shards without blocking a Tokio worker.
set_panic_reporter
Replace how shard drivers report isolated callback panics, for every runtime and every shard in the process. By default each panic prints eventful-rs: shard callback panicked to stderr; applications that own the terminal, such as TUIs, can route reports to a log instead.

Type Aliases§

DeliveryError
A tracked event handler failed to complete. Uses the same failure reasons as deferred shard invocations.

Attribute Macros§

action
Mark a method in an #[asynchronize] impl for fire-and-forget dispatch.
asynced
Mark a method in an #[asynchronize] impl for an async handle wrapper.
asynchronize
Generate handle wrappers for annotated methods in an inherent impl.
eventful
Add an events field and trait implementations needed for shard binding.
events
Define a typed event interface with synchronous &self methods. Generated signal-access extension traits and emission sets inherit the interface visibility, so private interfaces can use private payload types.
sharded
Select a shard for eventful types in an inline module, including nested inline modules. Paths are relative to the annotated module (e.g. super::Worker). Explicit eventful selections and nested scopes override the inherited choice. Out-of-line modules must select their own shard in their source file.
sharded_main
Run an async main function on a main-thread shard and join background shards.
slint_events
Turn explicitly declared Slint callbacks into a typed event interface.