Running a simple Scala.React expression

2019-07-19 17:12发布

问题:

I am looking into Scala.React, and the updated paper on the issue, trying to get a simple Signal based example to work.

I understand that the Signal method in the paper doesn't exist as such, but instead there are Strict and Lazy. So my naive first attempt:

Setting up the whole thing:

object dom extends scala.react.Domain {
  val engine    = new Engine
  val scheduler = new ManualScheduler
}
import dom._

Trying out composition:

val v1, v2 = Var(0)

val f = Strict { v1() + v2() }

The second line crashes with

java.lang.AssertionError: assertion failed: This method must be run on its domain
  scala.react.NilDebug@4eaf6cb1
    at scala.Predef$.assert(Predef.scala:179)
    at scala.react.Debug.assertInTurn(Debug.scala:37)
    at scala.react.EngineModule$Propagator.defer(EngineModule.scala:120)
        ...

So I must be doing something wrong. But what?


Second attempt:

scala> dom.start()

scala> var v1, v2, f = (null: Signal[Int])
v1: dom.Signal[Int] = null
v2: dom.Signal[Int] = null
f: dom.Signal[Int] = null

scala> schedule { v1 = Var(0); v2 = Var(0) }

scala> schedule { f = Strict { v1() + v2() }}

scala> engine.runTurn()

scala> schedule { println(f.now) }

scala> engine.runTurn()
Uncaught exception in turn!
scala.react.EngineModule$LevelMismatch$

回答1:

Ok, so first of all we should use Lazy instead of Strict if we want to keep a reference to those signals, because Strict requires to be run within a scheduled turn.

The following is my new attempt. Not sure if this is how it's intended, but it works:

object Test extends scala.react.Domain with App {
  val engine    = new Engine
  val scheduler = new ManualScheduler

  val v2   = Var(0)
  val v1   = Lazy { v2() + 10 }
  val f    = Lazy { v1() + v2() }

  start()

  schedule {
    new Observing {
      observe(f) { p =>
        println(s"Observed: $p")
      }
    }
    v2() = 5
  }

  runTurn()
}