Skip to content

Instantly share code, notes, and snippets.

@chandu0101
Last active August 29, 2015 14:23
Show Gist options
  • Save chandu0101/5169d198939267ec41ad to your computer and use it in GitHub Desktop.
Save chandu0101/5169d198939267ec41ad to your computer and use it in GitHub Desktop.
//snippets of rx and scalajs-react for my research ..
trait RxObserver extends OnUnmount {
def observe[T](rx: Rx[T])(f: T ⇒ Unit) = {
val obs = rx foreach f
onUnmount(obs.kill())
}
}
object RxObserver {
def install[P, S, B <: RxObserver, N <: TopNode] = OnUnmount.install[P, S, B, N]
}
class Backend(t: BackendScope[P, State]) extends RxObserver {
def onMount() = observe(t.props.rx)(newVal => t.modState(_.copy(field = newVal)))
}
case class Props(rx: Rx[Something])
case class State(field: Something)
def onMount() = {
onUnmount(controller.shutdown())
observe(controller.resourceOpt)(ro ⇒ t.modState(_.copy(resource = ro)))
observe(translatorController.translatorAndRuleMap)(tm ⇒ t.modState(_.copy(translators = tm)))
observe(transportController.transportMap)(tm ⇒ t.modState(_.copy(transports = tm)))
observe(controller.instDefs)(i ⇒ t.modState(_.copy(instructionDefs = i)))
observe(controller.dpTableDefs)(d ⇒ t.modState(_.copy(tables = d)))
observe(controller.dpDefs)(d ⇒ t.modState(_.copy(datapointDefs = d)))
observe(controller.datapoints)(d ⇒ t.modState(_.copy(datapoints = d)))
observe(controller.attrDefs)(a ⇒ t.modState(_.copy(attributeDefs = a)))
observe(controller.attributes)(a ⇒ t.modState(_.copy(attributes = a)))
}
//option 2 :
//todo: need to genericise this more. Currently the State can only be Option[S]
abstract class RxStateObserver[S](scope: BackendScope[_, Option[S]])
extends OnUnmount {
def setState(rxo: Option[Rx[S]]): Unit = scope.setState(rxo.map(_()))
def observe(rxo: Option[Rx[S]]): Unit = {
val obs = rxo.map(rx => rx.foreach(v => {
scope.setState(Some(v))
},true))
onUnmount {
obs.map(o => o.kill())
}
}
def observeAndSetState(rxo: Option[Rx[S]]): Unit = {
setState(rxo)
observe(rxo)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment