Created
November 3, 2017 17:06
-
-
Save adleong/71e757bf39602ca6bd3f22559d23be0b to your computer and use it in GitHub Desktop.
Var fun
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Base Var | |
alex-boron@ val base = Var(1) | |
base: Var[Int] with Updatable[Int] with Extractable[Int] = Var(1)@848564270 | |
// Derived Var using map (or flatMap, etc) | |
alex-boron@ val mapped = base.map { x => println("applying map"); x * 2 } | |
mapped: Var[Int] = com.twitter.util.Var$$anon$2@5d00e30e | |
// Observing the derived Var causes the map to be applied for each new observation | |
alex-boron@ val closable = mapped.changes.respond(println) | |
applying map | |
2 | |
closable: Closable = com.twitter.util.Closable$$anon$3@24facb47 | |
alex-boron@ closable.close() | |
res6: Future[Unit] = ConstFuture(Return(())) | |
// Create a reference counted Var that caches the value of a Var | |
alex-boron@ val stable = Var.async(mapped.sample()) { up => mapped.changes.respond(up.update) } | |
applying map | |
stable: Var[Int] = com.twitter.util.Var$$anon$4@184218af | |
// The first observation causes the map to be applied and the result cached | |
alex-boron@ val closable1 = stable.changes.respond(println) | |
applying map | |
2 | |
closable1: Closable = com.twitter.util.Closable$$anon$3@6225c800 | |
// Subsequent observations (as long as the Var remains observed) use the cached value | |
alex-boron@ val closable2 = stable.changes.respond(println) | |
2 | |
closable2: Closable = com.twitter.util.Closable$$anon$3@3fc261b7 | |
alex-boron@ val closable3 = stable.changes.respond(println) | |
2 | |
closable3: Closable = com.twitter.util.Closable$$anon$3@7953699e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment