R闪亮:异步downloadHandler

时间:2018-11-26 09:35:04

标签: r asynchronous shiny

我有一个闪亮的应用程序,需要大量时间下载zip文件。我正在尝试使用futurespromises软件包来管理下载,以便其他用户可以在下载进行时访问该应用。

该应用程序如下所示:

library(shiny)

ui <- fluidPage(
  downloadButton("Download", "Download")
)


server <- function(input, output){
  output$Download <- downloadHandler(
    filename = "Downloads.zip",
    content = function(file){
      withProgress(message = "Writing Files to Disk. Please wait...", {
        temp <- setwd(tempdir())
        on.exit(setwd(temp))
        files <- c("mtcars.csv", "iris.csv")

        write.csv(mtcars, "mtcars.csv")
        write.csv(iris, "iris.csv")



        zip(zipfile = file, files = files)
      })
    }
  )
}

shinyApp(ui, server)

我尝试将write.csv包装在future函数内并设置`,虽然这不会引发错误,但该应用程序在下载过程中对其他用户不可用。

library(shiny)
library(promises)
library(future)
plan(multiprocess)

ui <- fluidPage(
  downloadButton("Download", "Download")
)


server <- function(input, output){
  output$Download <- downloadHandler(
    filename = "Downloads.zip",
    content = function(file){
      withProgress(message = "Writing Files to Disk. Please wait...", {
        temp <- setwd(tempdir())
        on.exit(setwd(temp))
        files <- c("mtcars.csv", "iris.csv")

        future(write.csv(mtcars, "mtcars.csv"))
        future(write.csv(iris, "iris.csv"))



        zip(zipfile = file, files = files)
      })
    }
  )
}

shinyApp(ui, server)

我也尝试将整个downloadHandler函数包装在future函数中,但出现错误:

  

.subset2(x,“ impl”)$ defineOutput(name,value,label)中的错误:
  DownloadUnexpected的意外MulticoreFuture输出   DownloadUnexpected的MultiprocessFuture输出,   Download意外的环境输出以供下载

我如何异步处理整个downloadHandler?我正在使用闪亮服务器的开源版本。

1 个答案:

答案 0 :(得分:0)

不知道您是否还需要答案,但是我认为您已经很接近了。以后,我已经包装了write.csv和zip,如下所示,它在我的测试中适用于多个用户。

library(shiny)
library(promises)
library(future)
plan(multiprocess)

ui <- fluidPage(
  downloadButton("Download", "Download")
)


server <- function(input, output){
  output$Download <- downloadHandler(
    filename = "Downloads.zip",
    content = function(file){
      withProgress(message = "Writing Files to Disk. Please wait...", {
        temp <- setwd(tempdir())
        on.exit(setwd(temp))
        files <- c("mtcars.csv", "iris.csv")

        future({

        Sys.sleep(15)  
        write.csv(mtcars, "mtcars.csv")
        write.csv(iris, "iris.csv")



        zip(zipfile = file, files = files)})
      })
    }
  )
}

shinyApp(ui, server)