From da718d713cf786a8fde2b88c439834cb0b3fc90b Mon Sep 17 00:00:00 2001 From: Sarah Gerweck Date: Thu, 16 Apr 2015 00:38:58 -0700 Subject: [PATCH] Observable is a functor. --- .../org/gerweck/scalafx/util/package.scala | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/main/scala/org/gerweck/scalafx/util/package.scala b/src/main/scala/org/gerweck/scalafx/util/package.scala index 0e2dc0f..874280a 100644 --- a/src/main/scala/org/gerweck/scalafx/util/package.scala +++ b/src/main/scala/org/gerweck/scalafx/util/package.scala @@ -21,6 +21,24 @@ package object util { type Observable[A] = ObservableValue[A, _] type SimpleProperty[A] = Property[A, _] + implicit val observableFunctor = new Functor[Observable] { + def map[A, B](a: Observable[A])(f: A => B): Observable[B] = { + @inline def recalculate(): B = f(a.value) + + val originalValue = recalculate() + + val prop = ObjectProperty[B](originalValue) + + def changeHandler = { + prop.value = recalculate() + } + + a onChange changeHandler + prop + } + + } + implicit val observableApplicative = new Applicative[Observable] { def point[A](a: => A): Observable[A] = { ObjectProperty[A](a)