pub struct Context<A> { /* private fields */ }
Expand description

An actor execution context.

Implementations

Returns the address of the actor.

Returns the id of the actor.

Stop the actor.

Stop the supervisor.

this is ignored by normal actors

Create a stream handler for the actor.

Examples
use hannibal::*;
use futures::stream;
use std::time::Duration;

#[message(result = "i32")]
struct GetSum;

#[derive(Default)]
struct MyActor(i32);

#[async_trait::async_trait]
impl StreamHandler<i32> for MyActor {
    async fn handle(&mut self, _ctx: &mut Context<Self>, msg: i32) {
        self.0 += msg;
    }

    async fn started(&mut self, _ctx: &mut Context<Self>) {
        println!("stream started");
    }

    async fn finished(&mut self, _ctx: &mut Context<Self>) {
        println!("stream finished");
    }
}

#[async_trait::async_trait]
impl Handler<GetSum> for MyActor {
    async fn handle(&mut self, _ctx: &mut Context<Self>, _msg: GetSum) -> i32 {
        self.0
    }
}

#[async_trait::async_trait]
impl Actor for MyActor {
    async fn started(&mut self, ctx: &mut Context<Self>) -> Result<()> {
        let values = (0..100).collect::<Vec<_>>();
        ctx.add_stream(stream::iter(values));
        Ok(())
    }
}

#[hannibal::main]
async fn main() -> Result<()> {
    let mut addr = MyActor::start_default().await?;
    sleep(Duration::from_secs(1)).await; // Wait for the stream to complete
    let res = addr.call(GetSum).await?;
    assert_eq!(res, (0..100).sum::<i32>());
    Ok(())
}

Sends the message msg to self after a specified period of time.

We use Sender instead of Addr so that the interval doesn’t keep reference to address and prevent the actor from being dropped and stopped

Sends the message to self, at a specified fixed interval. The message is created each time using a closure f.

Sends the message msg to self, at a specified fixed interval.

Subscribes to a message of a specified type.

Unsubscribe to a message of a specified type.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.