pub struct Broker<T: Message<Result = ()>> { /* private fields */ }
Expand description

Message broker is used to support publishing and subscribing to messages.

Examples

use hannibal::*;
use std::time::Duration;

#[message]
#[derive(Clone)]
struct MyMsg(&'static str);

#[message(result = "String")]
struct GetValue;

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

#[async_trait::async_trait]
impl Actor for MyActor {
    async fn started(&mut self, ctx: &mut Context<Self>) -> Result<()>  {
        ctx.subscribe::<MyMsg>().await;
        Ok(())
    }
}

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

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

#[hannibal::main]
async fn main() -> Result<()> {
    let mut addr1 = MyActor::start_default().await?;
    let mut addr2 = MyActor::start_default().await?;

    Broker::from_registry().await?.publish(MyMsg("a"));
    Broker::from_registry().await?.publish(MyMsg("b"));

    sleep(Duration::from_secs(1)).await; // Wait for the messages

    assert_eq!(addr1.call(GetValue).await?, "ab");
    assert_eq!(addr2.call(GetValue).await?, "ab");
    Ok(())
}

Trait Implementations

Called when the actor is first started.

Called after an actor is stopped.

Construct and start a new actor, returning its address. Read more

Start a new actor, returning its address. Read more

Returns the “default value” for a type. Read more

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.