Actor Trait

Core traits for defining actors and message handlers.

Actor

The base trait for all actors. Any struct implementing this trait can be spawned and managed by the actor system.

1
2
3
4
5
6
7

Required Bounds

SendActor must be safe to send between threads
SizedActor size must be known at compile time
'staticActor cannot contain non-static references

Lifecycle Methods

fn started(&mut self, ctx: &mut Context<Self>)

Called once when the actor is spawned. Use for initialization, starting timers, or spawning children.

fn stopped(&mut self, ctx: &mut Context<Self>)

Called once when the actor stops. Use for cleanup, saving state, or releasing resources.

Handler

Synchronous message handler. Implement this for each message type your actor handles synchronously.

1
2
3

Type Parameters

M: MessageThe message type to handle

Methods

fn handle(&mut self, msg: M, ctx: &mut Context<Self>) -> M::Result

Process the message and return a result. Called synchronously - avoid blocking operations.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

AsyncHandler

Asynchronous message handler. Use this for handlers that need to perform async operations like I/O.

1
2
3
4
5

Methods

fn handle(&mut self, msg: M, ctx: &mut Context<Self>) -> BoxFuture<'_, M::Result>

Process the message asynchronously. Returns a boxed future that resolves to the result.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

StreamHandler

Handler for processing items from async streams. Use with ctx.add_stream().

1
2
3
4
5
6
7
8
9
10

Type Parameters

I: Send + 'staticThe stream item type

Methods

fn handle(&mut self, item: I, ctx: &mut Context<Self>)

Called for each item in the stream.

fn finished(&mut self, ctx: &mut Context<Self>)

Called when the stream ends. Default implementation does nothing.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

ActorId

Unique identifier for an actor instance.

1
2
3
4
5
6
7
8
9
10
11
12
13

Actor IDs are automatically generated when actors are spawned. Each ID is globally unique within the process.

ActorSystem

The root container for managing actors and their lifecycle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

Methods

pub fn new() -> Self

Create a new actor system.

pub fn spawn<A: Actor>(&self, actor: A) -> Addr<A>

Spawn a top-level actor with default mailbox capacity (256 messages).

pub fn spawn_with_capacity<A: Actor>(&self, actor: A, capacity: usize) -> Addr<A>

Spawn a top-level actor with custom mailbox capacity.

pub fn shutdown(&self)

Signal all actors to stop. Actors will complete current message and call stopped().

pub fn register<A: Actor>(&self, name: &str, addr: Addr<A>)

Register an actor by name. Auto-unregisters when actor stops.

pub fn lookup<A: Actor>(&self, name: &str) -> Option<Addr<A>>

Look up a registered actor by name.

Related