简体   繁体   中英

Downloading Reactive Objects in Shiny

Is it possible to download objects in shiny without having to create a separate, redundant, instance of that object within the downloadHandler() call? For example, consider the following example:

ui.R

library(shiny)

shinyUI(pageWithSidebar(
  headerPanel("Simple Example"),

  sidebarPanel(
    textInput("options","Enter some content:",""),
    submitButton("Go")
  ),

  mainPanel(
    tableOutput("dataTable"),
    downloadButton('downloadData','Save Data as CSV File')
  )
))

server.R

library(shiny)

shinyServer(function(input, output) {
  makeQuery <- reactive({
      if(input$options == ""){
        return("Enter some options")
      }
      else {
        return(input$options)
      }
  })

  runQuery <- function(query){
    dat <- data.frame(v1=rep(query,5))
    return(dat)
  }

  output$dataTable <- renderTable({
    query <- makeQuery()
    if(grepl("^Enter",query)){
      return(data.frame(Error=query))
    } else {
      return(runQuery(query))
    }
  },include.rownames=FALSE)

  output$downloadData <- downloadHandler(
    filename = c('data.csv'),
    content = function(file) {
      write.csv(runQuery(makeQuery()), file)
    }
  )

})

The issue I have with the above example is that I am running runQuery() within both the renderTable() and downloadHandler() calls. In this example there isn't really any extra overhead but in my real example this requires running a 5-10 minute process so it is extremely inefficient to call it twice whenever someone downloads the data.

Is there anyway that I can get around this issue by referencing an already created object in the downloadHandler() call or some other work around?

Yes! Turn the query from a function that you call from two places, into a reactive expression that you access from two places. Reactive expressions cache their results automatically.

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