【问题标题】:Use example of Scala ObservableSet TraitScala ObservableSet Trait 的使用示例
【发布时间】:2011-02-26 00:59:15
【问题描述】:

谁能帮我告诉我如何使用 scala 的 ObservableSet trait

非常感谢您

【问题讨论】:

    标签: scala collections set observablecollection scala-2.8


    【解决方案1】:

    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,但我无法立即正确输入,也没有花太长时间试图弄清楚。

    【讨论】:

    • 很好的例子。但是在第一个中缺少“val c = Counter(0)”。
    【解决方案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)
    

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

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多