Late reply from async io in Akka

I have been using akka for some time. I started to see some patterns in my code to solve the late answer for async io. Is this implementation ok? Is there another way to make the last answer without a block?

class ApplicationApi(asyncIo : ActorRef) extends Actor {
    // store senders to late reply
    val waiting = Map[request, ActorRef]()

    def receive = {
        // an actore request for a user, store it to late reply and ask for asyncIo actor to do the real job
        case request : GetUser => 
            waiting += (sender -> request)
            asyncIo ! AsyncGet("http://app/user/" + request.userId)
        // asyncio response, parse and reply
        case response : AsyncResponse =>
            val user = parseUser(response.body)
            waiting.remove(response.request) match {
                case Some(actor) => actor ! GetUserResponse(user)
            }
    }
}
+5
source share
1 answer

One way to avoid blocking while waiting for a response is to send using the ask-aka method ?, which returns Future(as opposed to !which returns ()).

Using the methods onSuccessor foreach, you can specify the actions that must be performed if / when the future is completed with a response. To use this, you need to mix in AskSupport:

class ApplicationApi(asyncIo : ActorRef) extends Actor with AskSupport {

  def receive = {
    case request: GetUser =>
      val replyTo = sender
      asyncIo ? AsyncGet("http://app/user/" + request.userId) onSuccess {
        case response: AsyncResponse =>
          val user = parseUser(response.body)
          replyTo ! GetUserResponse(user)
      }

}

, ApplicationApi, . .


, , sender , .

trait FromSupport { this: Actor =>
  case object from {
    def unapply(msg: Any) = Some(msg, sender)
  }
}

class MyActor extends Actor with FromSupport {
  def receive = {
    case (request: GetUser) from sender =>
      // sender is now a variable (shadowing the method) that is safe to use in a closure
  }
}
+5

All Articles