gpt4 book ai didi

scala - Akka确保毒丸被消耗

转载 作者:行者123 更新时间:2023-12-02 03:28:20 25 4
gpt4 key购买 nike

我想要一个在 Akka actor 处理 PoisonPill 时完成的 future 。

我试过:

一些引用?毒丸

但这永远不会完成。我认为你只能使用 '!'并不是 '?'。有什么想法吗?

最佳答案

如果您想要监视某个子 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 给你想要观看的 Actor ,并覆盖 postStop 完成 promise 。它看起来像这样:

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
}
}

希望对您有所帮助。干杯!

关于scala - Akka确保毒丸被消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28972877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com