First of all, thank for your answer!
Basing on your answer "object to be instantiated per session, you define it in the server" is something I've been looking for (this is the reason why I put results <- 0
in server
part according to https://shiny.rstudio.com/articles/scoping.html ). The problem is how to access this variable from the functions that I used in the example. Unfortunately, usage of do.call
and eval
with parse
are parts of the present application that I can't change.
Regarding application architecture - until now every "action" which does something and is trigerred by buttons worked separately using values stored in input
. Now more complicated "action" was introduced (code with calculations taking some time), so this would be wise to store "results" of these in case of re-usage.
To show this as real example, let's say we have simple app with 3 numericInput
-s and 4 actionButton
-s (ids: a1, a2, a3, a4). Buttons "a1" and "a2" trigger simple calculations (using values from numericInput
-s and executed via eval
with parse
) - so these can be rerun every time, because of short time of execution. Button "a3" triggers more complicated code - it takes for example 5 minutes (again using values from numericInput
-s and executed via eval
with parse
). Code which is attached to "a4" in 90% is similar with the code of "a3" - just adds something at the end, thus when "a3" was triggered it would be wise to reuse results of "a3" in "a4" instead of calculating everything again. The question is how to store results from "a3", hence these can be accessed in "a4"?
To recap, my problem is how to access results
from every parts of the app, taking into account that do.call
and eval
with parse
are widely used in this app and can't be simplified and every "action" code is source
-ed. In other words how to make my example work with all these do.call
and eval
with parse
:)?
Thank you!
Edit:
I've just modified the code to reflect usage of reactiveVal()
- I am not sure if implemented correctly.
# app.R
rm(list=ls())
library(shiny)
source("first.R")
source("second.R")
ui <- fluidPage(
actionButton("first", label = "First"),
actionButton("second", label = "Second")
)
server <- function(input, output, session) {
results <- reactiveVal(0)
observeEvent(input$first, {
first_parse()
})
observeEvent(input$second, {
second_summary()
})
}
shinyApp(ui, server)
# first.R
first_parse <- function(){
do.call(first_add, list())
}
first_add <- function(){
results(eval(parse(text = "(function(){return(10)})()")) )
}
# second.R
second_summary <- function(){
print(results() + 100)
}
After pressing "first" button I get:
Warning: Error in results: could not find function "results"
Stack trace (innermost first):
71: <Anonymous> [first.R#7]
70: do.call
[...]