Skip to content

Instantly share code, notes, and snippets.

@asaushkin
Last active March 18, 2019 05:18
Show Gist options
  • Save asaushkin/208634ea09b6f6fc216a670192b225e2 to your computer and use it in GitHub Desktop.
Save asaushkin/208634ea09b6f6fc216a670192b225e2 to your computer and use it in GitHub Desktop.
package playground
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
object ChildActorExercise extends App {
object WordCountMaster {
case class Initialize(workersCount: Int)
case class WordCountTask(origin: ActorRef, text: String)
case class WordCountReply(origin: ActorRef, count: Int)
}
class WordCountMaster extends Actor {
def mainLoop(workersIterator: Iterator[ActorRef]): Receive = {
case text: String =>
workersIterator.next() ! WordCountMaster.WordCountTask(sender(), text)
case WordCountMaster.WordCountReply(origin, count) =>
println(s"${self.path}: Count: $count")
origin ! count
}
override def receive: Receive = {
case WordCountMaster.Initialize(count) =>
val listOfActors =
for (c <- 1 to count) yield context.actorOf(Props[WordCountWorker], s"worker$c")
context.become(mainLoop(Iterator.continually(listOfActors).flatten))
}
}
class WordCountWorker extends Actor {
override def receive: Receive = {
case WordCountMaster.WordCountTask(origin, text) =>
println(s"${self.path}: I've got a message: $text")
sender() ! WordCountMaster.WordCountReply(origin, text.split(" ").length)
}
}
val system = ActorSystem.create("wordCountMaster")
val master = system.actorOf(Props[WordCountMaster], "master")
master ! WordCountMaster.Initialize(3)
master ! "Hello, World!"
master ! "Lorem ispum dorem"
master ! "There is some apples..."
master ! "Quick brown fox jumped over the..."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment