Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show progress bar for computation in eventReactive()?

Tags:

r

shiny

I want to show a progress bar if something in eventReactive() is evaluated. However, withProgress() doesn't seem to work as expected if nothing is added directly to the output. (See the first part below that gets triggered by input$go1.)

In a dashboard with multiple panels it shows up if one navigates to another subpage. However, I want to have it showing up immediately after hitting the button.

Can anybody help to fix this problem in the example below?

library(shiny)

ui <- fluidPage(
            actionButton("go1", "Go! Number 1"),
            actionButton("go2", "Go! Number 2"),
            plotOutput("plot")
            )



server <- function(input, output) {

    eventReactive(input$go1,{
        withProgress({
            for (i in 1:15) {
              incProgress(1/15)
              Sys.sleep(0.25)
              }
            }, message = "Doesn't show up!")
    })

output$plot <- renderPlot({
        input$go2
        withProgress({
            for (i in 1:15) {
                incProgress(1/15)
                Sys.sleep(0.1)
            }
        }, message = "Shows up!")
        plot(cars)
    })

}


shinyApp(ui = ui, server = server)
like image 217
Alex Avatar asked Dec 21 '25 16:12

Alex


1 Answers

eventReactive isn't executed when the event expression is triggered, it is only flagged as invalidated. You'll have to request their reactive value to have them executed - please check the following:

library(shiny)

ui <- fluidPage(
  actionButton("go1", "Go! Number 1"),
  actionButton("go2", "Go! Number 2"),
  plotOutput("plot")
)

server <- function(input, output) {

  myData <- eventReactive(input$go1, {
    withProgress({
      for (i in 1:15) {
        incProgress(1/15)
        Sys.sleep(0.25)
      }
    }, message = "Doesn't show up!")
    cars
  })

  output$plot <- renderPlot({
    input$go2
    req(myData())
    withProgress({
      for (i in 1:15) {
        incProgress(1/15)
        Sys.sleep(0.1)
      }
    }, message = "Shows up!")
    plot(myData())
  })

}

shinyApp(ui = ui, server = server)

For your example scenario observeEvent is the better choice. Please see this.

like image 101
ismirsehregal Avatar answered Dec 24 '25 07:12

ismirsehregal