akka - how to get results of several actors?

陌路散爱 提交于 2020-01-17 08:30:11

问题


I'm wondering if there any best practice to send 2 messages to 2 different actors

and wait for all of them (get results of course )in order to continue executing.

i.e something like:

send message to actor 1
send message to actor 2
List<results> = wait.all(actor1,actor2)

回答1:


You are probably looking for the ask pattern in combination with a Future.sequence or a for-comprehension:

import akka.pattern.ask

case object Request

implicit val timeout = Timeout(5 seconds) // needed for `?` below

// Ask your actors for a result
val f1 = actorA ? Request
val f2 = actorB ? Request
val f3 = actorC ? Request

// for-comprehension
(for {
    x <- f1
    s <- f2
    d <- f3
} yield (f1, f2, f3)).map {
    case (r1, r2, r3) =>
        //Do your stuff with the results
}

// Future.sequence
Future.sequence(f1, f2, f3).map {
    case (r1, r2, r3) =>
        //Do your stuff with the results
}


来源:https://stackoverflow.com/questions/44775946/akka-how-to-get-results-of-several-actors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!