Akka确保Poison Pill被消费

3
我希望在Akka actor处理PoisonPill后完成一个future。
我尝试过:
someRef?PoisonPill
但这永远不会完成。我认为只能使用'!'而不是'?'。有什么想法吗?
1个回答

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

希望它有所帮助。干杯!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接