这个问题是这个问题的延续:Is it possible to stop executing of R code inside shiny (without stopping the shiny process)?.
我在应用程序中显示的绘图需要一些时间才能生成,我希望用户能够停止创建(例如,如果他们在选项中出错).我在Shiny中找到了this blog post个关于使用callr
的答案.工作流程如下所示:
- 创建作业(job)/绘图的空列表
- 点击"开始"创建一个后台进程来创建绘图
首先,我不确定当几个人同时使用该应用程序时,它将如何扩展.由于每个后台进程都是独立的,我不认为一个用户会阻止其他用户,但我可能错了.
其次,我想在绘图上显示一个等待指示器.到目前为止,我使用包waiter
来实现这一点,但这里的问题是,renderPlot()
每秒都会失效,以判断后台进程是否完成.因此,当输出无效时,waiter
会反复出现和消失.
下面是一个模仿我想要的行为的示例应用程序:
library(shiny)
library(uuid)
library(ggplot2)
library(waiter)
ui <- fluidPage(
useWaiter(),
titlePanel("Test background job"),
actionButton("start","Start Job"),
actionButton("stop", "Stop job"),
plotOutput("plot")
)
# the toy example job
slow_func <- function(var){
library(ggplot2)
Sys.sleep(5)
ggplot(mtcars, aes(drat, !!sym(var))) +
geom_point()
}
server <- function(input, output, session) {
w <- Waiter$new(id = "plot")
token <- reactiveValues(var = NULL, id = NULL, last_id = NULL)
jobs <- reactiveValues()
# When I press "start", run the slow function and append the output to
# the list of jobs. To render the plot, check if the background process is
# finished. If it's not, re-check one second later.
long_run <- eventReactive(input$start, {
token$var <- c(token$var, sample(names(mtcars), 1))
token$id <- c(token$id, UUIDgenerate())
token$last_id <- token$id[[length(token$id)]]
message(paste0("running task with id: ", token$last_id))
jobs[[token$last_id]] <- callr::r_bg(
func = slow_func,
args = list(var = token$var[[length(token$var)]])
)
return(jobs[[token$last_id]])
})
observeEvent(input$start, {
output$plot <- renderPlot({
w$show()
if (long_run()$poll_io(0)["process"] == "timeout") {
invalidateLater(1000)
} else {
jobs[[token$last_id]]$get_result()
}
})
})
# When I press "stop", kill the last process, remove it from the list of
# jobs (because it didn't produce any output so it is useless), and display
# the last process (which by definition is the last plot produced)
observeEvent(input$stop, {
if (length(token$id) > 0) {
jobs[[token$last_id]]$kill()
message(paste0("task ", token$last_id, " stopped"))
token$id <- token$id[-length(token$id)]
if (length(token$id) > 0) {
token$last_id <- token$id[[length(token$id)]]
}
}
output$plot <- renderPlot({
if (length(token$id) > 0) {
print(token$last_id)
jobs[[token$last_id]]$get_result()
} else {
return(NULL)
}
})
})
}
shinyApp(ui = ui, server = server)
Current behavior:
- 运行应用程序,点击"开始工作"
- 请注意,
waiter
覆盖显示和消失
Question:在后台计算时,如何在绘图上获得恒定加载屏幕?