简体   繁体   中英

Shiny - Are reactive environments possible?

Right now, I have an expression that looks like this:

You can run this directly with a app.R file. It's standalone, and demonstrates the effect I want.

library(shiny)


rval <- reactiveValues()
rval$var <- new.env()
rval$flag <- FALSE

isolate({
  rval$var$a <- 1
  rval$var$b <- "Hello"
  rval$var$c <- c(1.2, 12.3, 123.0)
  rval$var$d <- list(1,2,"A")
})

ui <- navbarPage('reactiveTest',
  tabPanel('Analysis',
    fluidRow(
      actionButton("addVar", "Add a NULL var"),
      tableOutput('vars')
    ) 
  )
)

core_variable_table <- eventReactive(rval$flag == TRUE, {
  print(ls(rval$var))
  rval$flag <- FALSE

  df <- data.frame(ls(rval$var),
                   sapply(ls(rval$var), function(x){ class(get(x, envir = rval$var))}),
                   sapply(ls(rval$var), function(x){
                     y <- head(get(x, envir = rval$var))
                     if(is.null(y)) {
                       return("NULL")
                     } else {
                       return(toString(y))
                     }
                   })
  )
  rownames(df) <- seq(1, length(ls(rval$var)))
  colnames(df) <- c('Name', 'Type', 'Content')

  return(df)
})

dothis <- function(name, data) {
  observe({
    assign(x=name,
           value=data,
           envir=rval$var)
  })

  isolate({
    rval$flag <- TRUE
  })
}

server <- function(input, output, session) {
  output$vars <- renderTable({
      return(core_variable_table())
  })

  observeEvent(input$addVar, {
    rval$update
    dothis("gecko", NULL)
  })

}

shinyApp(ui, server)

As you can see, I'm trying to bind an entire environment as a variable, and I want changes to occur if any variable in that environment is modified. How might I bind the reactivity of Shiny outputs to an entire environment or the variables in that environment without having to use this terrible flag method?

Edit: Note that everything starts to come apart once I start having more than one function to trigger. I don't wish to have to flip 5 flags from one function--Shiny should have a way of doing things like this...

The fix that I've come up with is to instead generate the view of the environment based on a flag or integer increment. For example, if I modify any of the variables in the environment, I manually change a reactive variable that signals to the output of the application that it needs to update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM