【发布时间】:2021-10-28 20:44:42
【问题描述】:
我在下面的最小示例中模拟的场景是允许用户在长时间运行的下载(模拟Sys.sleep(10) 内 downloadHandler)。
在同步设置中,当点击“下载”按钮时,用户仍然可以与 UI 元素进行交互,但其他 Shiny 计算(在本例中为 renderText)会被放入队列中。我想要异步设置,在后台进行下载,用户仍然可以与 UI 元素交互并获得所需的输出(例如renderText)。
我正在使用callr::r_bg()在Shiny中实现异步,但问题是我当前的downloadHandler代码不正确(mtcars应该正在下载,但代码无法完成下载,404错误消息),我相信这是由于downloadHandler 期望编写content() 函数的特定方式,而我编写callr::r_bg() 的方式并不能很好地发挥作用。任何见解将不胜感激!
参考:
https://www.r-bloggers.com/2020/04/asynchronous-background-execution-in-shiny-using-callr/
小例子:
library(shiny)
ui <- fluidPage(
downloadButton("download", "Download"),
numericInput("count",
NULL,
1,
step = 1),
textOutput("text")
)
server <- function(input, output, session) {
long_download <- function(file) {
Sys.sleep(10)
write.csv(mtcars, file)
}
output$download <- downloadHandler(
filename = "data.csv",
content = function(file) {
x <- callr::r_bg(
func = long_download,
args = list(file)
)
return(x)
}
)
observeEvent(input$count, {
output$text <- renderText({
paste(input$count)
})
})
}
shinyApp(ui, server)
【问题讨论】: