Hit - laforge49/Asynchronous-Functional-Programming GitHub Wiki
Creating data structures from actors that can be incrementally serialized/deserialized is not always enough. Sometimes you need to attach some application logic. And you could even call the result a mobile actor. So lets look at a very simple application and see how it is done.
Consider an actor which keeps a hits counter which it increments every time it prints the counter. First we need a message, Hit, which the actor responds to.
case class Hit()
Now let's implement the logic as a component which is used to extend IncDesInt.
class HitComponent(actor: Actor) extends Component(actor) {
bind(classOf[Hit], hit)
def hit(msg: AnyRef, rf: Any => Unit) {
actor(Value()) {
rsp1 => {
val i = rsp1.asInstanceOf[Int] + 1
println("# of hits: " + i)
actor(Set(null, i))(rf)
}
}
}
}
We are also going to need a component factory.
object HitComponentFactory extends ComponentFactory {
override def instantiate(actor: Actor) = new HitComponent(actor)
}
Now we can implement a factory which binds this component to IncDesInt. We'll use a factory id of "hit".
class HitFactory extends IncDesIntFactory(FactoryId("hit")) {
include(HitComponentFactory)
}
We're done! Here's the test code.
val hitFactory = new HitFactory
val hit1 = hitFactory.newActor(null)
Future(hit1, Hit())
val bs = Future(hit1, Bytes()).asInstanceOf[Array[Byte]]
val hit2 = hitFactory.newActor(null).asInstanceOf[IncDes]
hit2.load(bs)
Future(hit2, Hit())
And the output.
# of hits: 1
# of hits: 2