pub trait ActorFuture<A: Actor> {
type Output;
// Required method
fn poll(
self: Pin<&mut Self>,
srv: &mut A,
ctx: &mut A::Context,
task: &mut Context<'_>,
) -> Poll<Self::Output>;
}
Expand description
Trait for types which are a placeholder of a value that may become available at some later point in time.
ActorFuture
is very similar to a regular Future
, only with subsequent combinator
closures accepting the actor and its context, in addition to the result.
ActorFuture
allows for use cases where future processing requires access to the actor or
its context.
Here is an example of a handler on a single actor, deferring work to another actor, and then updating the initiating actor’s state:
use actix::prelude::*;
// The response type returned by the actor future
type OriginalActorResponse = ();
// The error type returned by the actor future
type MessageError = ();
// This is the needed result for the DeferredWork message
// It's a result that combine both Response and Error from the future response.
type DeferredWorkResult = Result<OriginalActorResponse, MessageError>;
impl Handler<DeferredWork> for OriginalActor {
// Notice the `Response` is an `ActorFuture`-ized version of `Self::Message::Result`.
type Result = ResponseActFuture<Self, DeferredWorkResult>;
fn handle(&mut self, _msg: DeferredWork, _ctx: &mut Context<Self>) -> Self::Result {
// this creates a `Future` representing the `.send` and subsequent
// `Result` from `other_actor`
let update_self = self.other_actor
.send(OtherMessage {})
// Wrap that future so chained handlers can access the actor
// (`self` in the synchronous code) as well as the context.
.into_actor(self)
// once the wrapped future resolves, update this actor's state
.map(|result, actor, _ctx| {
match result {
Ok(v) => {
// update actor (self) state
actor.inner_state.update_from(v);
Ok(())
},
// Failed to send message to other_actor
Err(_e) => Err(()),
}
});
// box and return the wrapped future
Box::pin(update_self)
}
}
See also WrapFuture::into_actor()
which provides future conversion.