pub trait Actor: 'static + Send + Sized {
type Stop: Send + 'static;
// Required method
fn stopped(self) -> impl Future<Output = Self::Stop> + Send;
// Provided method
fn started(
&mut self,
mailbox: &Mailbox<Self>
) -> impl Future<Output = Result<(), Self::Stop>> + Send { ... }
}
Expand description
An actor which can handle message one at a time. Actors can only be
communicated with by sending messages through their Address
es.
They can modify their private state, respond to messages, and spawn other actors. They can also
stop themselves through their Context
by calling Context::stop_self
.
This will result in any attempt to send messages to the actor in future failing.
§Example
struct MyActor;
impl Actor for MyActor {
type Stop = ();
async fn started(&mut self, ctx: &Mailbox<Self>) -> Result<(), Self::Stop> {
println!("Started!");
Ok(())
}
async fn stopped(self) -> Self::Stop {
println!("Finally stopping.");
}
}
struct Goodbye;
impl Handler<Goodbye> for MyActor {
type Return = ();
async fn handle(&mut self, _: Goodbye, ctx: &mut Context<Self>) {
println!("Goodbye!");
ctx.stop_all();
}
}
// Will print "Started!", "Goodbye!", and then "Finally stopping."
smol::block_on(async {
let addr = xtra::spawn_smol(MyActor, Mailbox::unbounded());
addr.send(Goodbye).await;
smol::Timer::after(Duration::from_secs(1)).await; // Give it time to run
})
For longer examples, see the examples
directory.
Required Associated Types§
sourcetype Stop: Send + 'static
type Stop: Send + 'static
Value returned from the actor when Actor::stopped
is called.
Required Methods§
sourcefn stopped(self) -> impl Future<Output = Self::Stop> + Send
fn stopped(self) -> impl Future<Output = Self::Stop> + Send
Called at the end of an actor’s event loop.
An actor’s event loop can stop for several reasons:
- The actor called
Context::stop_self
. - An actor called
Context::stop_all
. - The last
Address
with aStrong
reference count was dropped.
Provided Methods§
Object Safety§
This trait is not object safe.