Created
February 17, 2012 19:27
-
-
Save derekwyatt/1855018 to your computer and use it in GitHub Desktop.
An experiment in receive method composition for Akka
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
| trait ReceiveComposiingActor extends Actor { | |
| trait Key | |
| lazy val receivePartials = scala.collection.mutable.Map.empty[Key, Receive] | |
| // Fronts 'context.become' to alter map before recomposition | |
| def becomeNew(key: Key, behaviour: Receive) { | |
| receivePartials += (key -> behaviour) | |
| context.become(composeReceive) | |
| } | |
| // composes behaviours. Obviously requires no intersection of domains | |
| def composeReceive = receivePartials.values.reduceLeft { (a, b) => a orElse b } | |
| // Annoying. The only way I could make things work. Initial creation of the | |
| // receive method is tough to get right. Just went for something that 'works' | |
| override def preStart() { | |
| context.become(composeReceive) | |
| } | |
| // essentially a dummy | |
| def receive = { case _ => } | |
| } | |
| class MyActor extends ReceiveComposingActor { | |
| object MainBehaviour extends Key | |
| object AuxBehaviour extends Key | |
| def mainBehaviourA: Receive = { | |
| case {whatever} => | |
| ... | |
| // Put in a new MainBehaviour, leave AuxBehaviour alone | |
| becomeNew(MainBehaviour, mainBehaviourB) | |
| } | |
| def mainBehaviourB: Receive = { ... } | |
| def auxBehaviourA: Receive = { | |
| case {whatever again} => | |
| ... | |
| // Put in a new AuxBehaviour, leave MainBehaviour alone | |
| becomeNew(AuxBehaviour, auxBehaviourB) | |
| } | |
| def auxBehaviourB: Receive = { ... } | |
| receivePartials += (MainBehaviour, mainBehaviourA) | |
| receivePartials += (AuxBehaviour, auxBehaviourA) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment