Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composing actors

Tags:

scala

akka

actor

I've implemented a Listenable/Listener trait that can be added to Actors. I'm wondering if it's possible to attach this style of trait to an actor without it having to explicitly call the listenerHandler method?

Also I was expecting to find this functionality in the Akka library. Am I missing something or is there some reason that Akka would not not include this?

trait Listenable { this: Actor =>
    private var listeners: List[Actor] = Nil

    protected def listenerHandler: PartialFunction[Any, Unit] = {
        case AddListener(who) => listeners = who :: listeners
    }

    protected def notifyListeners(event: Any) = {
        listeners.foreach(_.send(event))
    }
}

class SomeActor extends Actor with Listenable
{
    def receive = listenerHandler orElse {
        case Start => notifyListeners(Started())
        case Stop => notifyListeners(Stopped())
    }
}
like image 917
BefittingTheorem Avatar asked Mar 09 '10 20:03

BefittingTheorem


2 Answers

Why not extend Actor directly, or if you want non-Actors to be Listenable also, create a ListenableActor that extends Actor with Listenable?

You then would override receive in Actor as you've done above (except you'd want to call super.receive also, wouldn't you?--you'd just want to modify the function that's passed in).

like image 172
Rex Kerr Avatar answered Nov 16 '22 14:11

Rex Kerr


I suggest you extend Actor and use an abstract override.

like image 2
Daniel C. Sobral Avatar answered Nov 16 '22 14:11

Daniel C. Sobral