怎么样使用一个执着的缓存,运行应用程序一次,您可以根据需要手动更改所有输入(我还包括一个自动版本,我对此不太满意,可能会发生 b/c 竞争条件),然后在后续运行中,您可以正确获取所有值缓存?
library(shiny)
library(magrittr)
## change path to a non temp diretcory to keep that even after reboot
shinyOptions(cache = cachem::cache_disk(file.path(dirname(tempdir()),
"myapp-cache")))
xl <- 1:3
yl <- 1:3
ui <- fluidPage(
sliderInput("x", "x", min(xl), max(xl), min(xl), 1),
sliderInput("y", "y", min(yl), max(yl), min(yl), 1),
verbatimTextOutput("z"),
actionButton("fill", "Fill Cache")
)
server <- function(input, output, session) {
idx <- idy <- 1
r <- reactive({
message("Doing expensive computation...")
Sys.sleep(2) ## simulate expensive op
input$x + input$y
}) %>% bindCache(input$x, input$y)
observe({
req(input$fill)
if (idx != length(xl) + 1 || idy != length(yl)) {
## need the invalidateLater approach
## to allow shiny reacting on the change
## not sure whether we cannot trip over race conditions
## recommendation: do it once by hand (it's persistent anyways ;)
invalidateLater(500, session)
if (idx == length(xl) + 1) {
message("Updating y:", idy)
idx <<- 1
idy <<- idy + 1
updateSliderInput(session, "y", value = yl[[idy]])
} else {
message("Updating x:", idx)
updateSliderInput(session, "x", value = xl[[idx]])
idx <<- idx + 1
}
}
})
output$z <- renderText(r())
}
## Start app and set all values
shinyApp(ui, server)
## Close app and restart
## Cache is now filled
shinyApp(ui, server)