How to use "ask" for three values ​​in akka

I have an actor who sends a message to three actors and is waiting for the response of all three actors to continue. Actors return the data type of the form: List [(String, Double, String)]. I want all of them sorted according to the double value of Tuple3.

So far, the code that I wrote:

implicit val timeout = Timeout(5.seconds)
  val x = actorOne ? "hey"
  val y = actorTwo ? "you"
  val z = actorThree ? "there"
  val answer = for{
    a <- x.mapTo[List[(String, Double, String)]]
    b <- y.mapTo[List[(String, Double, String)]]
    c <- z.mapTo[List[(String, Double, String)]]
  } yield a ++ a ++ a sortBy(_._2)

How can I make sure the actor is not working until all three participants respond?

thank

+4
source share
2 answers

a, b c, . , , , onComplete:

answer.onComplete {
  case Success(x) => // do something on success
  case Failure(ex) => // report failure
}

Promise . . Future [Boolean], :

def myFunction():Future[Boolean] = {
  val p = Promise[Boolean]
  implicit val timeout = Timeout(5.seconds)
  val x = actorOne ? "hey"
  val y = actorTwo ? "you"
  val z = actorThree ? "there"
  val answer = for{
    a <- x.mapTo[List[(String, Double, String)]]
    b <- y.mapTo[List[(String, Double, String)]]
    c <- z.mapTo[List[(String, Double, String)]]
  } yield a ++ a ++ a sortBy(_._2)
  answer.onComplete {
    case Success(x) => 
       // do something with x
      p.success(true)
    case Failure(ex) =>
       // process faliure
      p.success(false)
  }
  p.future
}
+3

:

List((b1,2.03,b1), (c0,3.5,c0), (c0,3.5,c0), (b0,4.03,b0), (a0,4.1,a0), (a1,4.31,a1))

stdout ( "a" !).

: " , "?

  • -
  • "" , ?

  import scala.concurrent.{Future, Await}
  import scala.concurrent.duration._
  import akka.util.Timeout
  import scala.concurrent.ExecutionContext.Implicits.global


  implicit val timeout = Timeout(5.seconds)
  val x = Future(List(("a0", 4.1, "a0"), ("a1", 4.31, "a1")))
  val y = Future(List(("b0", 4.03, "b0"), ("b1", 2.03, "b1")))
  val z = Future(List(("c0", 3.5, "c0"), ("c0", 3.5, "c0")))
  val answer = for{
    a <- x.mapTo[List[(String, Double, String)]]
    b <- y.mapTo[List[(String, Double, String)]]
    c <- z.mapTo[List[(String, Double, String)]]
  } yield a ++ b ++ c sortBy(_._2)

  // don't use the result -> execute a side effect
  answer.foreach { res =>
    println(res)
  }


  // !!ONLY FOR TESTING!!
  Await.result(answer, 1.minute)
  Thread.sleep(1000)
0

All Articles