0
class A extends Actor{
   def act = {
    //do something
   }

}

val a = new A

a.join // How Can I implement it

I have read How can I join started Actor? however I still don't know how to write the code.

Community
  • 1
  • 1
worldterminator
  • 2,968
  • 6
  • 33
  • 52

2 Answers2

1

The standard way to achieve this would be to use the Ask Pattern

It goes something like this:

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

This is assuming that you want to block on a message from the actor. If you want to tell when an actor has died, you need to use DeathWatch like this:

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)
Tompey
  • 334
  • 2
  • 7
1

Simply use the gracefulStop pattern. This is example is directly from the 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 =>
}
David Weber
  • 1,965
  • 1
  • 22
  • 32