Handlers
Define how actors process messages.
The Handler Trait
For each message type an actor can receive, you implement the Handler trait:
The handler receives:
- →
&mut self— Mutable access to actor state - →
msg— The message being handled - →
ctx— The actor's context for spawning, timers, etc.
Async Handlers
For handlers that need to perform async operations (I/O, network calls), use AsyncHandler:
Sending to Async Handlers
Use the async-specific send methods:
Multiple Handlers
An actor can handle multiple message types:
Using Context in Handlers
The context provides powerful capabilities within handlers:
Stream Handlers
Handle items from async streams with StreamHandler:
Best Practices
Keep handlers fast
Sync handlers should complete quickly. Use AsyncHandler for I/O operations.
Return meaningful results
Use Result<T, E> types to communicate success/failure to callers.
Use the right handler type
Handler for CPU-bound work, AsyncHandler for I/O, StreamHandler for continuous data.
Don't block in sync handlers
Avoid std::thread::sleep or blocking I/O. It blocks all message processing.
Avoid panicking in handlers
Return errors instead. Panics trigger supervision but lose the response.
Handler Types Comparison
| Type | Use Case | Send Method |
|---|---|---|
Handler | Sync operations, state updates | send() |
AsyncHandler | Network, file I/O, database | send_async() |
StreamHandler | Continuous data (TCP, events) | ctx.add_stream() |
