pub fn ask<Msg, Ctx, R, T>(ctx: &Ctx, receiver: &T, msg: Msg) -> RemoteHandle<R>Expand description
Convenience fuction to send and receive a message from an actor
This function sends a message msg to the provided actor receiver
and returns a Future which will be completed when receiver replies
by sending a message to the sender. The sender is a temporary actor
that fulfills the Future upon receiving the reply.
futures::future::RemoteHandle is the future returned and the task
is executed on the provided executor ctx.
This pattern is especially useful for interacting with actors from outside of the actor system, such as sending data from HTTP request to an actor and returning a future to the HTTP response, or using await.
ยงExamples
#[derive(Default)]
struct Reply;
impl Actor for Reply {
type Msg = String;
fn recv(&mut self,
ctx: &Context<Self::Msg>,
msg: Self::Msg,
sender: Sender) {
// reply to the temporary ask actor
sender.as_ref().unwrap().try_tell(
format!("Hello {}", msg), None
).unwrap();
}
}
// set up the actor system
let sys = ActorSystem::new().unwrap();
// create instance of Reply actor
let actor = sys.actor_of::<Reply>("reply").unwrap();
// ask the actor
let msg = "Will Riker".to_string();
let r: RemoteHandle<String> = ask(&sys, &actor, msg);
assert_eq!(block_on(r), "Hello Will Riker".to_string());