How could you either approximate the reactive environment/behavior established by shiny functions or possibly even use these very functions in a
(Tried to leave this as a comment but S.O. said it was too long.)
Kudos for looking more closely at reactivity. You may find these two links helpful:
So actually Shiny's reactivity can be used outside of Shiny applications--with two tricks.
options(shiny.suppressMissingContextError=TRUE)
to make it go away.shiny:::flushReact()
. This is so that you can perform multiple updates and then let all the reactive code respond once, instead of recalculating with every update. For console use, you can ask Shiny to automatically call flushReact
on every console prompt by using shiny:::setAutoflush(TRUE)
. Again, this is only needed for observers to work.An example that works today (execute this line by line at the console):
library(shiny)
options(shiny.suppressMissingContextError=TRUE)
makeReactiveBinding("x_1")
x_1 <- Sys.time()
x_2 <- reactive(x_1 + 60*60*24)
x_1
x_2()
x_1 <- Sys.time()
x_1
x_2()
# Now let's try an observer
shiny:::setAutoflush(TRUE)
observe(print(paste("The time changed:", x_1)))
x_1 <- Sys.time()
I would recommend taking another look at leveraging Shiny's reactive abstractions more directly. I think you can achieve a syntax like this quite straightforwardly with makeActiveBinding
(assuming you think this is better than what Shiny gives you today):
where <- new.reactr()
where$x_1 <- Sys.time()
where$x_2 <- reactive(x_1 + 60*60*24)
where$x_1 # Read x_1
where$x_2 # Read x_2
One key advantage to declaring reactive expressions using reactive()
rather than setThis
is that the former can easily and naturally model expressions that depend on multiple reactive values/expressions at once. Note that reactive expressions are both cached and lazy: if you modify x_1
it will not actually recalculate x_2
until you try to read x_2
, and if you read x_2
again without x_1
having changed then it'll just return the previous value without recalculating.
For a more functional twist on Shiny reactivity, see Hadley Wickham's new package https://github.com/hadley/shinySignals that is inspired by Elm.
Hope that helps.