9

In C#, classes and interfaces can have events:

public class Foo
{
    public event Action SomethingHappened;

    public void DoSomething()
    {
        // yes, i'm aware of the potential NRE
        this.SomethingHappened();
    }
}

This facilitates a push-based notification with minimal boilerplate code, and enables a multiple-subscriber model so that many observers can listen to the event:

var foo = new Foo();
foo.SomethingHappened += () => Console.WriteLine("Yay!");
foo.DoSomething();  // "Yay!" appears on console. 

Is there an equivalent idiom in Scala? What I'm looking for is:

  1. Minimal boilerplate code
  2. Single publisher, multiple subscribers
  3. Attach/detach subscribers

Examples of its use in Scala documentation would be wonderful. I'm not looking for an implementation of C# events in Scala. Rather, I'm looking for the equivalent idiom in Scala.

FMM
  • 4,049
  • 1
  • 23
  • 44
  • 1
    this may be helpful: http://stackoverflow.com/questions/6814246/in-scala-how-would-i-combine-event-driven-programming-with-a-functional-approac – daryal Jan 24 '13 at 14:23

2 Answers2

2

Idiomatic way for scala is not to use observer pattern. See Deprecating the Observer Pattern.

Take a look at this answer for implementation.

Community
  • 1
  • 1
senia
  • 36,859
  • 4
  • 83
  • 123
2

This is a nice article how to implement C# events in Scala Think it could be really helpful.

Base event class;

class Event[T]() {

  private var invocationList : List[T => Unit] = Nil

  def apply(args : T) {
    for (val invoker <- invocationList) {
      invoker(args)
    }
  }

  def +=(invoker : T => Unit) {
    invocationList = invoker :: invocationList
  }

  def -=(invoker : T => Unit) {
    invocationList = invocationList filter ((x : T => Unit) => (x != invoker))
  }

}

and usage;

val myEvent = new Event[Int]()

val functionValue = ((x : Int) => println("Function value called with " + x))
myEvent += functionValue
myEvent(4)
myEvent -= functionValue
myEvent(5)
myuce
  • 1,103
  • 1
  • 17
  • 26
Ph0en1x
  • 9,545
  • 6
  • 45
  • 91
  • From the question: "I'm not looking for an implementation of C# events in Scala." – FMM Jan 24 '13 at 14:55
  • 2
    Please, if you post a link, provide at least basic excerpt: as the time goes on, page may become unavailable and future reader wouldn't have any direction to dig into. – om-nom-nom Jan 24 '13 at 20:34