Scala Akka Play, the future does not return

I am using Scala 2.10, Akka 2.1 and Play 2.1. When I send an HTTP request to my server, I am ask

one actor to compute something. The idea is to return the result of the calculation if it returns before timeout, otherwise there will be another line. See code below.

val futureInt: Future[Int] = ask(testActor, Calculate(number.toInt)).mapTo[Int]
val timeoutFuture = play.api.libs.concurrent.Promise.timeout("Oops", 2.seconds)

Async {
  Future.firstCompletedOf(Seq(futureInt, timeoutFuture)).map {
    case i: Int => Ok("Got result " + i)
    case t: String => Ok("timeout expired")
  }
}

      

The actor looks like this:

class TestActor() extends Actor {
  def receive = {
    case Calculate(tonumber: Int) =>
      for (a <- 1 to tonumber) {
        val c: Double = scala.math.pow(a, 2)
        println("a: " + a + ", c: " + c)
      }
      12345 // hardcoded value to return when the calculation finishes
    case _ =>
      println("bah")
  }
}

      

My problem is that even if the actor ends before the timeout expires, nothing is returned by "Future" and so the timeout always expires. What am I doing wrong? Many thanks.

+3


source to share


1 answer


From http://doc.akka.io/docs/akka/snapshot/scala/actors.html

Using ask will send a message to the receiving Actor, just like saying, and the receiving Actor must respond with the sender! response to complete the returned future with a value.

and



Attention

To complete the future with an exception, you need to send an error message to the sender. This does not happen automatically when the actor throws an exception while processing a message.

So, instead of "returning" like you do in a normal scala function, do something on the lines

def receive = {
  case Calculate(tonumber: Int) =>
    ...
    sender ! 12345
  case _ =>
    sender ! akka.actor.Status.Failure(new InvalidArgumentException)
}

      

+3


source







All Articles