使用Scala ObservableSet Trait的示例

时间:2010-05-31 15:53:25

标签: scala collections set observablecollection scala-2.8

有人可以帮我告诉我如何使用scala的 ObservableSet 特质吗?

非常感谢您提前

2 个答案:

答案 0 :(得分:8)

ObservableSet是从Publisher特征延伸的特征,给出了一些基本的发布订阅行为。使用它的一个简单例子是:

scala> class Counter(var count: Int) extends Publisher[String] {
          def inc(): Unit = {
              count += 1
              super.publish("updated count to: " + count)
          }
     }

scala> class S[Evt, Pub] extends Subscriber[Evt, Pub] {
         def notify(pub: Pub, event: Evt): Unit = println("got event: " + event)
      }
defined class S

scala> val s = new S[String, Counter#Pub]     
s: S[String,Counter#Pub] = S@7c27a30c

scala> val c = new Counter(1)
c: Counter = Counter@44ba70c

scala> c.subscribe(s)

scala> c.inc
got event: updated count to: 2

ObservableSet执行类似的操作,在使用+ =或+ - 方法添加或删除元素时调用publish方法,请参阅以下示例(如上所述定义类S):

scala> class MySet extends HashSet[Int] with ObservableSet[Int] {       
     override def +=(elem: Int): this.type = super.+=(elem);
     override def -=(elem: Int): this.type = super.-=(elem);
     override def clear: Unit = super.clear;      
}

defined class MySet

scala> val set = new MySet
set: MySet = Set()

scala> val subS = new S[Any, Any]
subCol: S[Any,Any] = S@3e898802

scala> set.subscribe(subS)

scala> set += 1
got event: Include(NoLo,1)
res: set.type = Set(1)

我通过使用类型Any定义S而懒惰,但我无法立即获得正确的输入,并且没有花太多时间试图解决它。

答案 1 :(得分:2)

对于所有打字信息,这是一个眼睛,但这是我能够让它工作的方式。我欢迎有关如何使打字更简洁的建议。 各种编辑,包括类型别名

import collection.mutable._
import collection.script._

val set = new HashSet[String] with ObservableSet[String] { }

type Msg = Message[String] with Undoable
type Sub = Subscriber[Msg, ObservableSet[String]]

val sub = new Sub() {
  def notify(pub: ObservableSet[String], event: Msg): Unit = {
    println("%s sent %s".format(pub, event))
    event match {
      case r:Remove[_] => println("undo!"); event.undo()
      case _ => 
    }
  }
}

set.subscribe(sub)

set += "foo"
set += "bar"
set -= "bar"

打印:

Set(foo) sent Include(NoLo,foo)
Set(bar, foo) sent Include(NoLo,bar)
Set(foo) sent Remove(NoLo,bar)
undo!
Set(bar, foo) sent Include(NoLo,bar)

有趣的是,撤消导致另一条消息被发布......