Last active
August 29, 2015 14:07
-
-
Save mariussoutier/7207a6601d58a5215829 to your computer and use it in GitHub Desktop.
Use typed message in actors
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
class MyActor extends TypedMessageActor { | |
import MyActor._ | |
def receive = ReceiveMessage[AllowedMessage] { | |
case Message1(text) => | |
... | |
case Message2 => | |
... | |
} | |
} | |
object MyActor { | |
sealed trait AllowedMessage | |
case class Message1(text: String) extends AllowedMessage | |
case object Message2 extends AllowedMessage | |
} |
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
/** | |
* Actor that can enforce messages from a common sub-type. Just define your receive methods using | |
* `ReceiveMessage[MessageType]`, where MessageType should be a sealed trait in your companion object. | |
*/ | |
trait TypedMessageActor extends Actor { | |
/** | |
* Use this method to define a "typed" receive, and define a handler for messages that do not conform to this type. | |
*/ | |
def ReceiveAndHandleMessage[MSG: ClassTag](rm: PartialFunction[MSG, Unit])(unhandled: Any => Unit): Receive = { | |
case m: MSG => rm(m) | |
case x => unhandled(x) | |
} | |
/** | |
* Use this method to define a "typed" receive. | |
* This does not prevent receiving other messages, it will just make it easier to declare what types of messages are | |
* handled. The actor fail when a non-handled message is received. | |
* received. | |
*/ | |
def ReceiveMessage[MSG: ClassTag](rm: PartialFunction[MSG, Unit]): Receive = | |
ReceiveAndHandleMessage(rm)(m => sys.error(s"Message $m is not recognized by ${this.getClass.getSimpleName}")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment