Expand description
Lightweight, runtime-agnostic actor pattern with dynamic error types.
Works with tokio, async-std, or blocking threads. Uses flume channels.
§Quick Start
ⓘ
use std::io;
use actor_helper::{Handle, act_ok};
// Public API
pub struct Counter {
handle: Handle<CounterActor, io::Error>,
}
impl Counter {
pub fn new() -> Self {
Self { handle: Handle::spawn(CounterActor { value: 0 }).0 }
}
pub async fn increment(&self, by: i32) -> io::Result<()> {
self.handle.call(act_ok!(actor => async move {
actor.value += by;
})).await
}
pub async fn get(&self) -> io::Result<i32> {
self.handle.call(act_ok!(actor => async move { actor.value })).await
}
pub async fn is_running(&self) -> bool {
self.handle.state() == ActorState::Running
}
}
// Private actor
struct CounterActor {
value: i32,
}§Error Types
Use any error type implementing ActorError:
io::Error(default)anyhow::Error(withanyhowfeature)StringBox<dyn Error>
§Blocking/Sync
ⓘ
// Use spawn_blocking and call_blocking instead of spawn and call
let (handle, _) = Handle::<MyActor, io::Error>::spawn_blocking(MyActor { value: 0 });
handle.call_blocking(act_ok!(actor => async move { actor.value }))?;§Custom Loops
Use spawn_with / spawn_blocking_with for custom receive loops (e.g. tokio::select!):
ⓘ
use actor_helper::{Handle, Receiver, Action};
let (handle, _) = Handle::<MyActor, io::Error>::spawn_with(
MyActor { value: 0 },
|mut actor, rx| async move {
loop {
tokio::select! {
Ok(action) = rx.recv_async() => action(&mut actor).await,
_ = some_background_task() => { /* ... */ },
else => break Ok(()),
}
}
},
);§Notes
- Actions run sequentially, long tasks block the mailbox
- Panics are caught and converted to errors with location info
callrequirestokioorasync-stdfeaturecall_blockinghas no feature requirements
Macros§
Structs§
- Handle
- Cloneable handle to send actions to actor
Awith error typeE.
Enums§
- Actor
State - Represents the current state of an actor.
Traits§
- Actor
Error - Convert panic/actor-stop messages into your error type.
Functions§
- block_
on - Execute async futures in blocking context. Run a future to completion on the current thread.
Type Aliases§
- Action
- Action sent to an actor:
FnOnce(&mut A) -> Future<()>. - Actor
Fut - Pinned, boxed future used by action helpers and macros.
- PreBox
Actor Fut - Unboxed future type for actor actions.
- Receiver
- Flume unbounded receiver. Actors receive actions via
Receiver<Action<Self>>. - Sender
- Flume unbounded sender.