我正在尝试以闪亮的方式创建下载处理程序,但使用 future_promise() 因为写入文件可能需要一些时间。这是我想做的一个工作示例,但不使用异步框架:
一个正常工作的 .Rmd 闪亮应用程序:当您单击按钮时,它会将 10 个随机偏差写入文件并将其作为下载提供。我添加了 5 秒的延迟。
---
title: "download, no futures"
runtime: shiny
output: html_document
---
```{r setup, include=FALSE}
library(dplyr)
knitr::opts_chunk$set(echo = FALSE)
```
This version works.
```{r}
renderUI({
button_reactive <- reactive({
y = rnorm(10)
Sys.sleep(5)
tf = tempfile(fileext = ".txt")
cat(c(y,'\n'), sep='\n', file = tf)
d = readBin(con = tf, what = "raw", n = file.size(tf))
return(list(fn = basename(tf), d = d))
})
output$button <- downloadHandler(
filename = function() {
button_reactive() %>%
`[[`('fn')
},
content = function(f) {
d = button_reactive() %>%
`[[`('d')
con = file(description = f, open = "wb")
writeBin(object = d, con = con)
close(con)
}
)
shiny::downloadButton(outputId = "button", label="Download")
})
我正在尝试使用 future_promise 在异步框架中实现这一点。这是 {future}/{promises} 版本:
---
title: "download futures"
runtime: shiny
output: html_document
---
```{r setup, include=FALSE}
library(future)
library(promises)
plan(multisession)
library(dplyr)
knitr::opts_chunk$set(echo = FALSE)
```
This version yields this error on download attempt, reported in the R console:
```
Warning: Error in enc2utf8: argument is not a character vector
[No stack trace available]
```
```{r}
renderUI({
button_reactive <- reactive({
future_promise({
y = rnorm(10)
Sys.sleep(5)
tf = tempfile(fileext = ".txt")
cat(c(y,'\n'), sep='\n', file = tf)
d = readBin(con = tf, what = "raw", n = file.size(tf))
return(list(fn = basename(tf), d = d))
}, seed = TRUE)
})
output$button <- downloadHandler(
filename = function() {
button_reactive() %...>%
`[[`('fn')
},
content = function(f) {
con = file(description = f, open = "wb")
d = button_reactive() %...>%
`[[`('d') %...>%
writeBin(object = ., con = con)
close(con)
}
)
shiny::downloadButton(outputId = "button", label="Download")
})
当我在 Firefox 中单击按钮时,我没有得到任何文件,在 R 控制台中,显示如下:
Warning: Error in enc2utf8: argument is not a character vector
[No stack trace available]
经过一些调试后,我相信会发生这种情况,因为无论运行下载处理程序的什么都在运行该filename
函数,期待一个字符向量,并获得一个承诺。但我不确定如何解决这个问题。
我看到了这个问题,其中提问者似乎有同样的问题,但没有提供解决方案(他们的例子不可复制)。
我怎样才能解决这个问题?