Last active
March 18, 2019 05:18
-
-
Save asaushkin/208634ea09b6f6fc216a670192b225e2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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