|
Akka/Scala example source code file (Listeners.scala)
The Listeners.scala Akka example source code
/**
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package akka.routing
import akka.actor.{ Actor, ActorRef }
import java.util.{ Set, TreeSet }
sealed trait ListenerMessage
final case class Listen(listener: ActorRef) extends ListenerMessage
final case class Deafen(listener: ActorRef) extends ListenerMessage
final case class WithListeners(f: (ActorRef) ⇒ Unit) extends ListenerMessage
/**
* Listeners is a generic trait to implement listening capability on an Actor.
* <p/>
* Use the <code>gossip(msg)</code> method to have it sent to the listeners.
* <p/>
* Send <code>Listen(self)</code> to start listening.
* <p/>
* Send <code>Deafen(self)</code> to stop listening.
* <p/>
* Send <code>WithListeners(fun)</code> to traverse the current listeners.
*/
trait Listeners { self: Actor ⇒
protected val listeners: Set[ActorRef] = new TreeSet[ActorRef]
/**
* Chain this into the receive function.
*
* {{{ def receive = listenerManagement orElse … }}}
*/
protected def listenerManagement: Actor.Receive = {
case Listen(l) ⇒ listeners add l
case Deafen(l) ⇒ listeners remove l
case WithListeners(f) ⇒
val i = listeners.iterator
while (i.hasNext) f(i.next)
}
/**
* Sends the supplied message to all current listeners using the provided sender() as sender.
*
* @param msg
* @param sender
*/
protected def gossip(msg: Any)(implicit sender: ActorRef = Actor.noSender): Unit = {
val i = listeners.iterator
while (i.hasNext) i.next ! msg
}
}
Other Akka source code examplesHere is a short list of links related to this Akka Listeners.scala source code file: |
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.