Last active
November 27, 2017 00:02
-
-
Save ryantanner/7085445 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
case class User(id: Long, name: String) | |
class Work { /* ... */ } | |
class Result { /* --- */ } | |
case class WorkToBeDone(user: User, work: Work) | |
case class WorkIsDone(user: User, result: Result) | |
class Worker extends Actor { /* ... */ } | |
class BadWorkerCoordinator extends Actor { | |
implicit val timeout = Timeout(5 seconds) | |
import context.dispatcher | |
def receive = { | |
case WorkToBeDone(user, work) => | |
val worker = context.actorOf(Props[Worker]) | |
(worker ask work) foreach { case WorkIsDone(user, result) => | |
sender ! result | |
} | |
} | |
} | |
class GoodWorkerCoordinator extends Actor { | |
// Map of requester actors by user | |
var requesters = Map.empty[User, ActorRef] | |
def receive = { | |
case WorkToBeDone(user, work) => | |
context.actorOf(Props[Worker]) ! work | |
requesters += user -> sender | |
case WorkIsDone(user, result) if requesters.isDefinedAt(user) => | |
requesters.get(user) foreach { case requester => | |
requester ! result | |
requesters -= user | |
} | |
} | |
} | |
class BetterWorkerCoordinator extends Actor { | |
def coordinate(requesters: Map[User, ActorRef]): Receive = { | |
case WorkToBeDone(user, work) => | |
context.actorOf(Props[Worker]) ! work | |
context.become(coordinate(requesters + (user -> sender))) | |
case WorkIsDone(user, result) if requesters.isDefinedAt(user) => | |
requesters.get(user) foreach { case requester => | |
requester ! result | |
context.become(coordinate(requesters - user)) | |
} | |
} | |
def receive = coordinate(Map.empty[User, ActorRef]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment