Trait xtra::Actor

source ·
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 Addresses. 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§

source

type Stop: Send + 'static

Value returned from the actor when Actor::stopped is called.

Required Methods§

source

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:

Provided Methods§

source

fn started( &mut self, mailbox: &Mailbox<Self> ) -> impl Future<Output = Result<(), Self::Stop>> + Send

Called as soon as the actor has been started.

Object Safety§

This trait is not object safe.

Implementors§