Skip to content

Instantly share code, notes, and snippets.

@przemek-pokrywka
Created March 2, 2014 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save przemek-pokrywka/9315172 to your computer and use it in GitHub Desktop.
Save przemek-pokrywka/9315172 to your computer and use it in GitHub Desktop.
How to get None when reduction was not applied and Some(value) when it did in scala.rx
package frp
import rx._
import rx.ops._
object Demo extends App {
case class Val[+T](value: T, reduced: Boolean = false) {
def toOpt = if (reduced) Some(value) else None
}
implicit class MyRxOps[+T](val source: Rx[T]) extends AnyVal{
def reducedOnly[A >: T](combiner: (A, A) => A): Rx[Option[A]] = {
source.map(Val(_)) reduce { (a: Val[A], b: Val[A]) =>
Val(combiner(a.value, b.value), reduced = true)
} map (_.toOpt)
}
}
val price = Var(1)
val deltas = price.reducedOnly((oldVal, newVal) => newVal - oldVal)
println(deltas()) // there was only one price, so deltas should be None
price() = 2
println(deltas()) // price went up by 1
price() = 3
println(deltas()) // price went up by 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment