Skip to content

Instantly share code, notes, and snippets.

@neilw4
Created October 8, 2015 22:42
Show Gist options
  • Save neilw4/c3a12d6805b61f172310 to your computer and use it in GitHub Desktop.
Save neilw4/c3a12d6805b61f172310 to your computer and use it in GitHub Desktop.
import scala.collection.mutable.{HashMap, MultiMap, LinkedHashSet, Set}
import scala.reflect.runtime.universe._
trait OrderedMultiMap[K, V] extends MultiMap[K, V] {
override def makeSet: Set[V] = new LinkedHashSet[V]
}
object Listener {
trait Manager {
private val listeners = new HashMap[Type, Set[Any => Unit]] with OrderedMultiMap[Type, Any => Unit]
def addListener[E: TypeTag](listener: E => Unit) {
listeners.addBinding(typeOf[E], listener.asInstanceOf[Any => Unit])
}
def removeListener[E: TypeTag](listener: E => Unit) {
listeners.removeBinding(typeOf[E], listener.asInstanceOf[Any => Unit])
}
protected def getListeners[E: TypeTag]() = listeners.get(typeOf[E]).asInstanceOf[List[E => Unit]]
protected def notify[E: TypeTag](event: E) {
getListeners[E].foreach(_.apply(event))
}
}
object Test extends Manager {
case class A(i: Int)
case class B(s: String)
case class C(i: Int, B: String)
def printA(a: A) = {
print("A"); print(a)
}
def printB(b: B) = {
print("B"); print(b)
}
addListener(printA)
val a = new A(1)
notify(3) // does nothing
notify(a) // calls printA once
addListener(printA)
notify(a) // calls printA twice
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment