scala - Returning to "sender" from a future inside an actor -
this question has answer here:
- sender inside future 2 answers
i want -
class myactor extends actor { .... override def receive = { case msg => .... // future { ... // calculate response sender ! response } } } // in other code - val future = myactorref ? msg future.onsuccess { .... }
would work? in other words, akka's "ask" implementation care if response sent before "receive" method finishes or not?
yes work, , there built-in akka pattern - pipe
:
import akka.pattern.pipe override def receive = { case msg => .... // future { ... // calculate response response } pipeto sender() }
there are, caveats in code should note:
sender
function, therefore, when code inside future{...}
block executes, actor may handling message sender, may reply wrong sender. avoid this, evaluate sender outside closure:
val mysender = sender() future { ... // calculate response mysender ! response }
you don't need worry if use pipe
.
you wrapping future actor , calling actor ask
, again gives future. should consider calling future directly, without actors. if need actor, e.g. because you're isolating mutable state or message ordering important, should aware computing future
not happen on actor's thread, losing state consistency , message ordering - reason consider losing actor, , calling future directly.
Comments
Post a Comment