Last active
September 30, 2024 23:56
-
-
Save 3xau1o/0112bf173ef59faa4c02e7610e6281e6 to your computer and use it in GitHub Desktop.
Scala basic signal
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
| // Translated from https://www.youtube.com/watch?v=bUy4xiJ05KY | |
| import scala.collection.mutable.ListBuffer | |
| var RUNNING: Option[() => Any] = None | |
| class Signal[T](initial: T) { | |
| private var _value = initial | |
| private var observers = ListBuffer[() => Any]() | |
| def apply(): T = | |
| // running function may be implicit param instead global var | |
| RUNNING match | |
| case Some(f) => this.observers += f | |
| case None => () | |
| _value | |
| def value: T = apply() | |
| def value_=(value: T): Unit = | |
| if (this._value == value) return | |
| this._value = value | |
| this.onChanged() | |
| def onChanged(): Unit = | |
| this.observers.foreach(_.apply()) | |
| } | |
| def runAndExtractDependencies[T](f: () => T): Unit = | |
| RUNNING = Some(f) | |
| f() | |
| RUNNING = None | |
| val numberSignal = Signal(0) | |
| val stringSignal = Signal("hello") | |
| runAndExtractDependencies(() => { | |
| val msg = "from 1 " | |
| println(msg + numberSignal.value) | |
| println(msg + stringSignal.value) | |
| }) | |
| numberSignal.value = 5 | |
| stringSignal.value = "world" | |
| runAndExtractDependencies(() => { | |
| val msg = "from 2 " | |
| println(msg + numberSignal.value) | |
| println(msg + stringSignal.value) | |
| }) | |
| numberSignal.value = 3 | |
| stringSignal.value = "test" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment