Last active
January 8, 2017 12:43
-
-
Save PKOfficial/a9d56def7379dc9ee51f850adf854f26 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.concurrent._ | |
import scala.concurrent.duration._ | |
import akka.actor.{Actor, ActorRef, ActorSystem, Props} | |
import akka.pattern.ask | |
import akka.util.Timeout | |
// KillMe case object to stop an actor | |
case object KillMe | |
// TellMyPath case object to print actor's path | |
case object TellMyPath | |
object ActorSelectionExample extends App { | |
implicit val timeout = Timeout(5 seconds) | |
// Actor system | |
val system = ActorSystem("actor-system") | |
// ActorRef point to actor named parent | |
val parent = system.actorOf(Props[MyActor], "parent") | |
// ActorRef point to actor named "child" which is child of above actor "parent" | |
val child = Await.result((parent ? (Props[Child], "child")).mapTo[ActorRef], Duration.Inf) | |
// Print actor path using actorRef | |
child ! TellMyPath | |
// ActorSelection point to same actor as of "child" | |
val newChild = system.actorSelection("/user/parent/child") | |
// Print actor path using ActorSelection | |
newChild ! TellMyPath | |
// Killing actor | |
child ! KillMe | |
// Print actor path which has been killed | |
child ! TellMyPath | |
Thread.sleep(100) | |
// Creating another child actor with same name as previous | |
val anotherChild = Await.result((parent ? (Props[Child], "child")).mapTo[ActorRef], Duration.Inf) | |
// Print actor path using new ActorRef | |
anotherChild ! TellMyPath | |
// Print actor path using with old ActorSelection | |
newChild ! TellMyPath | |
// Terminating actor system | |
system.terminate() | |
} | |
class Child extends Actor { | |
override def receive: Receive = { | |
case TellMyPath => | |
val actorName = self.path | |
println(s"Child with path: $actorName") | |
case KillMe => | |
context.stop(self) | |
} | |
} | |
class MyActor extends Actor { | |
override def receive: Receive = { | |
case (prop: Props, name: String) => | |
val child = context.actorOf(prop, name) | |
sender ! child | |
case _ => println("Invalid :(") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment