Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One way to avoid blocking while waiting for a reply is to send using the <code>ask</code> method—a.k.a. <code>?</code> operator—which returns a <code>Future</code> (unlike <code>!</code> which returns <code>()</code>).</p> <p>Using the <code>onSuccess</code> or <code>foreach</code> methods, you can specify actions to be performed if/when the future is completed with a reply. To use this you need to mix in the <a href="http://doc.akka.io/api/akka/2.0.3/#akka.pattern.AskSupport" rel="nofollow"><code>AskSupport</code></a> trait:</p> <pre><code>class ApplicationApi(asyncIo : ActorRef) extends Actor with AskSupport { def receive = { case request: GetUser =&gt; val replyTo = sender asyncIo ? AsyncGet("http://app/user/" + request.userId) onSuccess { case response: AsyncResponse =&gt; val user = parseUser(response.body) replyTo ! GetUserResponse(user) } } </code></pre> <p>Avoid using this technique to perform any side effect that modifies the state of the <code>ApplicationApi</code> actor, because the effect will happen out-of-sync with the receive loop. Forwarding messages to other actors should be safe, though.</p> <hr> <p>By the way, here is a trick to capture the current <code>sender</code> as part of the pattern match, avoiding the need to assign it to a variable later.</p> <pre><code>trait FromSupport { this: Actor =&gt; case object from { def unapply(msg: Any) = Some(msg, sender) } } class MyActor extends Actor with FromSupport { def receive = { case (request: GetUser) from sender =&gt; // sender is now a variable (shadowing the method) that is safe to use in a closure } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload