class A extends Actor{
def act = {
//do something
}
}
val a = new A
a.join // How Can I implement it
我看过How can I join started Actor? 但是我仍然不知道如何编写代码。
答案 0 :(得分:1)
实现这一目标的标准方法是使用Ask Pattern
它是这样的:
class MyActor extends Actor {
def receive = {
case "Ping" => sender ! "Pong"
}
}
val future = actor ? "Ping"
val result = Await.result(future, 10 seconds) //blocks until the response has been received, or the timeout reached
这假设您要阻止来自actor的消息。如果你想知道演员何时死亡,你需要像这样使用DeathWatch:
case object TellMeWhenActorDies
case object ActorDied
class Watcher extends Actor {
val child = context.actorOf(Props[Watched], "watched")
context.watch(child)
override def receive: Receive = {
case TellMeWhenActorDies => context.become(waitingForDeath(sender))
}
def waitingForDeath(client: ActorRef): Receive = {
case Terminated(name) => client ! ActorDied
}
}
class Watched extends Actor {
override def receive: Receive = {
case _ => //do nothing
}
}
val finishedFuture = supervisor ? TellMeWhenActorDies
system.actorSelection("/user/$a/watched").tell(PoisonPill, supervisor)
Await.result(finishedFuture, 10 seconds)
答案 1 :(得分:0)
只需使用gracefulStop模式即可。这个例子直接来自Akka docs:
try {
val stopped: Future[Boolean] = gracefulStop(actorRef, 5 seconds, Manager.Shutdown)
Await.result(stopped, 6 seconds)
// the actor has been stopped
} catch {
// the actor wasn't stopped within 5 seconds
case e: akka.pattern.AskTimeoutException =>
}