Context API

Runtime context providing access to actor capabilities.

Context<A>

The Context is passed to lifecycle hooks and handlers, providing methods for spawning children, setting timers, watching actors, and more.

1
2
3

Identity

pub fn address(&self) -> Addr<A>

Get this actor's address. Useful for passing to other actors or registering.

pub fn id(&self) -> ActorId

Get this actor's unique identifier.

Lifecycle Control

pub fn stop(&self)

Signal this actor to stop. The actor will finish processing the current message, then call stopped() and terminate.

Spawning Children

pub fn spawn_child<C>(&mut self, child: C) -> Addr<C>

Spawn a child actor. Children automatically stop when parent stops. Parent receives Terminated when child stops.

pub fn spawn_child_with_capacity<C>(&mut self, child: C, capacity: usize) -> Addr<C>

Spawn a child with custom mailbox capacity.

pub fn spawn_child_with_strategy<C, F>(&mut self, factory: F, strategy: SupervisorStrategy) -> Addr<C>

Spawn a child with a supervision strategy. The factory is called to create new instances on restart.

pub fn spawn_child_with_strategy_and_capacity<C, F>(&mut self, factory: F, strategy: SupervisorStrategy, capacity: usize) -> Addr<C>

Spawn a child with both custom strategy and mailbox capacity.

Death Watch

pub fn watch<B>(&self, addr: &Addr<B>)

Watch another actor. This actor will receive a Terminated message when the watched actor stops.

Note: Child actors are automatically watched. You only need to call watch() for actors that aren't your children.

Timers

pub fn run_later<M>(&self, delay: Duration, msg: M) -> TimerHandle

Send a message to self after a delay. Returns a handle that can cancel the timer.

pub fn run_interval<M>(&self, interval: Duration, msg: M) -> TimerHandle

Send a message to self repeatedly at fixed intervals. Message must implement Clone.

Streams

pub fn add_stream<S, I>(&mut self, stream: S)

Add an async stream to be processed by this actor. Items are handled via StreamHandler.

Streams are polled alongside the message mailbox. Items are processed in the order they arrive.

TimerHandle

Handle returned by timer methods for cancellation.

1
2
3
4
5
6
7
8
9
10
11
12
pub fn cancel(&self)

Cancel the timer. If already fired, this has no effect.

pub fn is_cancelled(&self) -> bool

Check if the timer was cancelled.

Related