Skip to content

Instantly share code, notes, and snippets.

@tldeti
Created January 23, 2018 08:41
Show Gist options
  • Save tldeti/93d55ddce8a786af276492ffa8fa9aab to your computer and use it in GitHub Desktop.
Save tldeti/93d55ddce8a786af276492ffa8fa9aab to your computer and use it in GitHub Desktop.
sealed trait Ref[T]{
def get:T
def registWatcher(f:()=>Unit):Unit
}
case class ElemRef[T](var v:T) extends Ref[T]{
override def get: T = v
var callbacks:Vector[()=>Unit] =Vector()
def set(x:T) = {
v = x
callbacks.foreach(x=>x())
}
def map[B](f:T=>B) = new RefF(this,f)
def registWatcher(f:()=>Unit) = callbacks = callbacks :+ f
}
case class RefF[A,B](ref:Ref[A],f:A=>B) extends Ref[B]{
var v = f(ref.get)
override def get = v
registWatcher(()=>v = f(ref.get))
def registWatcher(f:()=>Unit) =
ref.registWatcher(f)
}
object Test extends App{
val a = ElemRef(List(1,2,3))
val b = a.map(x=>{
println("b func execute")
x.filter(x=>x<2)
})
println(b.get)
println(b.get)
a.set(List(1,1,2,3,4))
println(b.get)
}
@tldeti
Copy link
Author

tldeti commented Jan 23, 2018

b func execute
List(1)
List(1)
b func execute
List(1, 1)

Process finished with exit code 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment