简体   繁体   English

对于C#的事件,Scala中惯用的等价物是什么

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

In C#, classes and interfaces can have event s: 在C#中,类和接口可以有event

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? 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. 在Scala文档中使用它的例子非常棒。 I'm not looking for an implementation of C# events in Scala. 我不是在寻找Scala中C#事件的实现 Rather, I'm looking for the equivalent idiom in Scala. 相反,我正在寻找Scala中的等效成语

Idiomatic way for scala is not to use observer pattern. scala的惯用方法不是使用观察者模式。 See Deprecating the Observer Pattern . 请参阅弃用观察者模式

Take a look at this answer for implementation. 看看这个答案的实施。

This is a nice article how to implement C# events in Scala Think it could be really helpful. 这是一篇很好的文章,如何在Scala中实现C#事件。想想它可能真的很有帮助。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM