如何实现Shiny应用中输出计算完成即渲染而非批量渲染?
实现Shiny应用输出的异步渲染(完成即显示)
开发包含多个输出的Shiny应用时,默认所有输出会等待全部计算完成后才一起渲染。要让每个输出在自身计算完成后立即显示(比如示例中让distPlot先于distPlot_2渲染),可以借助promises和future包实现异步计算,避免阻塞其他输出的渲染流程。
解决方案步骤
- 安装并加载
promises与future包 - 配置多进程计算环境,让耗时任务在后台执行
- 将耗时的输出渲染逻辑用异步方式改写
修改后的完整代码
library(shiny) library(promises) library(future) # 配置多进程异步计算 plan(multisession) # Define UI for application that draws a histogram ui <- fluidPage( # Application title titlePanel("Old Faithful Geyser Data"), # Sidebar with a slider input for number of bins sidebarLayout( sidebarPanel( sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30) ), # Show a plot of the generated distribution mainPanel( plotOutput("distPlot"), plotOutput("distPlot_2"), ) ) ) # Define server logic required to draw a histogram server <- function(input, output) { output$distPlot <- renderPlot({ # generate bins based on input$bins from ui.R x <- faithful[, 2] bins <- seq(min(x), max(x), length.out = input$bins + 1) # draw the histogram with the specified number of bins hist(x, breaks = bins, col = 'darkgray', border = 'white') }) output$distPlot_2 <- renderPlot({ # 用future_promise包裹耗时逻辑,实现异步计算 future_promise({ x <- faithful[, 2] Sys.sleep(3) bins <- seq(min(x), max(x), length.out = input$bins + 1) hist(x, breaks = bins, col = 'darkgray', border = 'white') }) }) } # Run the application shinyApp(ui = ui, server = server)
关键说明
plan(multisession):设置多进程环境,让异步任务在独立的后台进程中运行,不阻塞主进程的输出渲染future_promise():将耗时的计算逻辑(这里是带Sys.sleep(3)的绘图代码)包裹起来,让Shiny在等待该任务完成时,先处理并渲染其他已完成的输出(比如distPlot)
调整滑块后,distPlot会立刻完成渲染并显示,3秒后distPlot_2才会显示出来,实现了“计算完成即渲染”的需求。
内容的提问来源于stack exchange,提问作者jstuebner
相关产品推荐
相关产品推荐

