我想在Akka演员处理PoisonPill时完成未来。
我试过了:
someRef? PoisonPill
但这永远不会完成。我想你只能用'!'并不是 '?'。有什么想法吗?
答案 0 :(得分:1)
如果您想要监视某个子actor的生命周期,您只需watch
该actor并根据您的逻辑处理Terminated
消息。例如:
class MyActor extends Actor {
import context._ // to avoid writing context everywhere
val child = actorOf(Props(new ChildActor)) // ChildActor is the type of the actor you are monitoring, the child
watch(child) // subscribe to the Terminated message of the child
override def receive: Receive = {
case "kill" ⇒ child ! PoisonPill // kill the child. You could also use context.stop(child)
case Terminated(`child`) ⇒ println("child died") // handle the termination of the child. Use back-ticks to make child a stable identifier
case _ ⇒ println("meh") // who cares
}
}
现在,如果你想要一个明确的Future
,我想到的第一件事就是将Promise
传递给你想要观看的演员,并覆盖postStop
来完成诺言。它看起来像这样:
class MyActor(p: Promise[Unit]) extends Actor { // receive the Promise to complete
override def receive: Receive = {
case _ ⇒ println("meh") // who cares
}
override def postStop(): Unit = { // after stopped
p.tryComplete(Success(())) // complete the promise
}
}
object Main {
def main(args: Array[String]) {
val system = ActorSystem("test")
val p = Promise[Unit]()
val f = p.future // get the future from the promise
val a = system.actorOf(Props(new MyActor(p))) // send the promise to the actor you want to watch
f onSuccess { // register a callback when the future completes
case _ ⇒ println("actor died")
}
a ! "foo"
a ! PoisonPill
}
}
希望它有所帮助。干杯!