执行长时间计算时更新actionButton

时间:2019-04-29 13:19:36

标签: r button shiny loading

我有一个shiny::actionButton,它触发了很长的计算。我想更新正在执行计算的操作按钮标签,但似乎无法正常工作。

这是一个最小的工作示例:

library(shiny)

ui <- fluidPage(actionButton("button", "Calculate"))

server <- function(session, input, output) {
  observeEvent(input$button, {
    print("start calculation")
    updateActionButton(session, "button", "Calculating...")

    # emulate calculation
    Sys.sleep(3)

    print("finish calculation")
    updateActionButton(session, "button", "Calculate")
  })
}

shinyApp(ui, server)

但是按钮似乎没有改变。看起来该按钮仅显示最后updateActionButton的内容,而忽略之前的任何内容。

如何使actionButton正确更新?

1 个答案:

答案 0 :(得分:0)

您可以使用进度条,而不用更改按钮标签。
例如

ui <- fluidPage(actionButton("button", "Calculate"))

server <- function(session, input, output) {
  observeEvent(input$button, {
    #print("start calculation")
    updateActionButton(session, "button", "Calculating...")
    progress <- Progress$new(session, min=1, max=15)
    on.exit(progress$close())

    progress$set(message = 'Calculation in progress',
                 detail = 'This may take a while...')

    # emulate calculation
    #Sys.sleep(3)
    for (i in 1:6) {
      progress$set(value = i)
      Sys.sleep(0.5)
    }

    print("finish calculation")
    updateActionButton(session, "button", "Calculate")

    session$sendCustomMessage(type = 'testmessage', message = 'Selected Points were set positive.')
  })
}

shinyApp(ui, server)

reporting_progress处查看更多详细信息。