Scala Listener/Observer

Jeb picture Jeb · Sep 20, 2010 · Viewed 10.5k times · Source

Typically, in Java, when I've got an object who's providing some sort of notification to other objects, I'll employ the Listener/Observer pattern.

Is there a more Scala-like way to do this? Should I be using this pattern in Scala, or is there something else baked into the language I should be taking advantage of?

Answer

Alex Cruise picture Alex Cruise · Sep 20, 2010

You can still accumulate a list of callbacks, but you can just make them functions instead of having to come up with yet another single method interface.

e.g.

case class MyEvent(...)

object Foo { 
  var listeners: List[MyEvent => ()] = Nil

  def listen(listener: MyEvent => ()) {
    listeners ::= listener
  }

  def notify(ev: MyEvent) = for (l <- listeners) l(ev) 
}

Also read this this somewhat-related paper if you feel like taking the red pill. :)