summaryrefslogtreecommitdiff
path: root/test/disabled/presentation/akka/src/akka/routing/Listeners.scala
blob: 04f6c1259f5490e74aa75bead323b9963d3217d7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * Copyright (C) 2009-2011 Scalable Solutions AB <http://scalablesolutions.se>
 */

package akka.routing

import akka.actor.{ Actor, ActorRef }
import java.util.concurrent.ConcurrentSkipListSet
import scala.collection.JavaConversions._

sealed trait ListenerMessage
case class Listen(listener: ActorRef) extends ListenerMessage
case class Deafen(listener: ActorRef) extends ListenerMessage
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 =>
  private val listeners = new ConcurrentSkipListSet[ActorRef]

  protected def listenerManagement: Receive = {
    case Listen(l)        => listeners add l
    case Deafen(l)        => listeners remove l
    case WithListeners(f) => listeners foreach f
  }

  protected def gossip(msg: Any) = listeners foreach (_ ! msg)
}