shiny.worker icon indicating copy to clipboard operation
shiny.worker copied to clipboard

How to use shiny.worker with downloadHandler

Open latlio opened this issue 2 years ago • 0 comments

Thanks for developing shiny.worker. I'm trying to use shiny.worker to handle downloads asynchronously. I'm aware that it's possible with future, but I'd like to be able to try this using shiny.worker. The scenario is that I'd like the renderText to update while a download is occurring in the background. I've placed the write.csv with Sys.sleep(10) within the worker$run_job to simulate a long-running process that I'd like to delegate to the background. However, there are two things that I think are wrong with this code, and I don't know how to approach them:

  1. I don't think write.csv(mtcars, file) is able to find the file arg in the parent content = function(file) environment
  2. It's not clear what I should specify in the args_reactive arg of worker$run_job given that it's a download button with no input$...

My minimal reprex is below:

library(shiny.worker)

worker <- initialize_worker()

ui <- fluidPage(
  downloadButton("download", "Download"),
  
  numericInput("count",
               NULL,
               1,
               step = 1),
  
  textOutput("text")
)

server <- function(input, output, session) {
  
  output$text <- renderText({
      paste(input$count)
  })
  
  output$download <- downloadHandler(
    filename = "data.csv",
    content = function(file) {
      worker$run_job("test", function(file = file) {
        temp <- setwd(tempdir())
        on.exit(setwd(temp))
        Sys.sleep(10)
        write.csv(mtcars, file)
    }
  )
}

shinyApp(ui, server)

latlio avatar Oct 29 '21 15:10 latlio