You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny异步编程multisession计划未按手册描述生效问题排查

问题描述

尝试在Shiny中实现异步编程,但无法成功运行。原本预期在等待10秒生成表格的过程中,系统时间会每秒刷新一次,但实际主会话被Sys.sleep()占用,无法执行该操作。请问我的逻辑理解哪里出现了错误?

原代码

library(shiny)
library(future)
library(promises)
plan(multisession)

ui <- fluidPage(
  
  shiny::selectInput("select", "select", choices = c("iris","mtcars")),
  
  tableOutput("table")
)

server <- function(input,output,session) {
  
  output$table<- renderTable(
    {
      
      select <- input$select
      future_promise(
        {
          Sys.sleep(10)
          get(select)
        }
      ) %...>%
        data.frame()
    }
    
  )
  
  # 检查主会话是否被耗时操作占用
  observe(
    {
      invalidateLater(1000,session = session)
      print(Sys.time())
    }
  )
}

shinyApp(ui,server)
解答

你的核心问题在于两处:

  • 多余的%...>% data.frame()管道操作干扰了Shiny对promise的识别,导致future_promise中的代码意外在主会话同步执行,阻塞了会话。
  • get(select)返回的iris/mtcars本身就是data.frame类型,无需再用data.frame()转换。

修改后的正确代码如下:

library(shiny)
library(future)
library(promises)
plan(multisession)

ui <- fluidPage(
  shiny::selectInput("select", "select", choices = c("iris","mtcars")),
  tableOutput("table")
)

server <- function(input,output,session) {
  
  output$table <- renderTable({
    selected_data <- input$select
    future_promise({
      Sys.sleep(10)
      get(selected_data)
    })
  })
  
  observe({
    invalidateLater(1000, session = session)
    print(Sys.time())
  })
}

shinyApp(ui,server)

修改后,future_promise会将耗时的Sys.sleep()和数据加载操作放到后台进程执行,主会话不会被阻塞,observe中的系统时间会每秒正常刷新,10秒后表格会自动渲染出来。

另外需要确保你的R包版本满足要求:Shiny ≥ 1.1.0、promises ≥ 1.1.0、future ≥ 1.17.0,这是Shiny异步功能正常运行的前提。

内容的提问来源于stack exchange,提问作者René

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 14:53:12