Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Listener/Observer

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?

like image 506
Jeb Avatar asked Sep 20 '10 20:09

Jeb


People also ask

Is observer and listener the same?

The Observer pattern (also known as Listener, or Publish-Subscribe) is particularly useful for graphical applications. The general idea is that one or more objects (the subscribers) register their interest in being notified of changes to another object (the publisher).

Why do we need observer pattern?

Professional Logo Design Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.

What is Observer interface?

Observer is a behavioral design pattern that allows some objects to notify other objects about changes in their state. The Observer pattern provides a way to subscribe and unsubscribe to and from these events for any object that implements a subscriber interface.


1 Answers

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. :)

like image 129
Alex Cruise Avatar answered Sep 18 '22 13:09

Alex Cruise