Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the idiomatic equivalent in Scala for C#'s event

Tags:

c#

scala

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.

like image 897
FMM Avatar asked Jan 24 '13 14:01

FMM


1 Answers

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

Take a look at this answer for implementation.

like image 122
senia Avatar answered Sep 21 '22 05:09

senia