我正在设计一个演员系统。centerActor 需要等待 actor1 和 actor2 的结果才能响应客户端。
在中心演员:
def receive: Receive ={
case request => {
implicit val timeout = Timeout(1.seconds)
val ask1 = actor1 ? Update1.mapTo[Int]
val ask2 = actor2 ? Update2.mapTo[String]
val response =
(for(x <- ask1; y <- ask2) yield Done).recover{case _ => FailReply}
response pipeTo sender
}
}
在这种设计中,我的发件人(客户端)无法接收Done
消息。我不知道为什么。所以我在考虑第二种设计:
def receive: Receive = {
implicit val timeout = Timeout(1.seconds)
case request => {
val ask1 = actor1 ? Update1.mapTo[Int]
val ask2 = actor2 ? Update2.mapTo[String]
val response =
(for(x <- ask1; y <- ask2) yield Done).recover{case _ => FailReply})
response pipeTo self
context.become(waiting(sender))
}
}
def waiting(s: ActorRef) = {
case Done =>
s ! Done
unstashAll()
context.unbecome()
case FailReply => s ! FailReply
case _ => stash()
}