Could anyone help me telling me how to use scala's ObservableSet trait?
Thank you very much in advance
ObservableSet is a trait extending from the Publisher trait, giving some basic publish subscribe behaviour. A simple example of using this would be:
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 does something similar, it calls the publish method when elements are added or removed with the += or +- method, see the following example (with class S defined as above):
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)
I've beem lazy by defining S with types Any, but I couldn't get the typing right immediately, and haven't spend too long trying to figure it out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With