Shiny session-global variable

Ok. A version of your app that works...

# app.R
library(shiny)

#source("first.R")
# first.R
first_parse <- function(){  
  do.call(first_add, list())
}

first_add <- function(){  
  eval(parse(text = "(function(){return(10)})()"))
}

#source("second.R")
# second.R
second_summary <- function(input){  
  print(input + 100)  
  return(input+100)
}
ui <- fluidPage(
  actionButton("first", label = "First"),  
  actionButton("second", label = "Second"),
  verbatimTextOutput("vtext")
)

server <- function(input, output, session) {
  results <- reactiveVal(0)
  observeEvent(input$first, {
    # update value of results - replace with 10
    results(first_parse())
  })  
  observeEvent(input$second, {
    # update value of results - add 100
    results(second_summary(results()))
  })
  output$vtext <- renderText(paste("Results:",results()))
}

shinyApp(ui, server)

A few remaining thoughts:

  • Obviously your examples are contrived, but hopefully as you start reading / thinking about functional programming, you will see how liberating it is. I.e. your first function literally just returns the value 10. There may be cause for rearchitecting (read: removing needless complications) some of the code into separate functions (or an internal package) that perform individual tasks
  • For instance, rather than "code-generating" with eval and parse, it is more likely that functional programming will solve your issue of different parameters, etc.
  • You may profit from the discussion about the First line of every R script?
  • Notice what I did to the second function. This adheres to better "function" best-practices
  • The verbatimTextOutput is just there to show what is happening.
  • Rather than save the values in separate files, I thought it easier just to put the code where it would be sourced.
  • The results() function / reactiveVal only exists inside the server function, so it should not be directly referred to elsewhere.
4 Likes