Skip to content

Instantly share code, notes, and snippets.

@daviscabral
Forked from ryantanner/AntiPatterns.scala
Last active August 29, 2015 14:16
Show Gist options
  • Save daviscabral/e3c63d22b98bf87b070f to your computer and use it in GitHub Desktop.
Save daviscabral/e3c63d22b98bf87b070f to your computer and use it in GitHub Desktop.
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