views:

211

answers:

2

Could anyone help me telling me how to use scala's ObservableSet trait?

Thank you very much in advance

+7  A: 
Arjan Blokzijl
Thanks a lot, very usefull!
isola009
+2  A: 

It's a bit of an eyesore with all the typing information, but this is how I was able to get it to work. I welcome suggestions on how to make the typing more concise. various edits including type aliases:

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"

That prints:

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)

Interestingly, undo caused another message to be published...

huynhjl
Thanks a lot, very usefull!
isola009