Skip to content

Instantly share code, notes, and snippets.

@2m
Created September 2, 2014 09:11
Show Gist options
  • Save 2m/1695454e19fff3260dc8 to your computer and use it in GitHub Desktop.
Save 2m/1695454e19fff3260dc8 to your computer and use it in GitHub Desktop.
Stackable trait with context.become
package stackable
import akka.actor.{Props, ActorSystem, Actor}
object Main extends App {
val sys = ActorSystem("stackable")
val act = sys.actorOf(Props[EchoActor])
act ! "BooHoo"
act ! "BooHoo"
act ! "BooHoo"
System.in.read()
sys.shutdown()
sys.awaitTermination()
}
trait Behaviour { self: Actor =>
var wrapped: Receive = _
def receive: Receive = {
case msg => if (wrapped.isDefinedAt(msg)) wrapped(msg) else unhandled(msg)
}
}
trait FunnyTracer extends Behaviour { self: Actor =>
override def receive = {
case msg =>
println("Mooo!")
super.receive(msg)
println("Oink oink!")
}
}
class EchoActor extends Actor with FunnyTracer {
def statefulReceive: Int => Receive = (i: Int) => {
case msg =>
println(s"Received $msg while storing $i")
wrappedBecome(statefulReceive(i+1))
}
def wrappedBecome(r: Receive) = {
wrapped = r
}
wrappedBecome(statefulReceive(0))
}
> sbt run
Mooo!
Received BooHoo while storing 0
Oink oink!
Mooo!
Received BooHoo while storing 1
Oink oink!
Mooo!
Received BooHoo while storing 2
Oink oink!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment