Jayman McAllister
Jayman McAllister

Reputation: 49

Issue updating render text from within a loop

I am trying to figure out how to cause rendertext to update for each iteration through a loop. I am trying to create a status bar where some text is output for each cycle through the loop. Currently the text is displayed only after the loop has completed, displaying the last value from the list. The updateprogressbar works completely fine.

Any suggestions?

A minimal reproducible can be found below.

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  tags$h4(textOutput("loadingtxt")),
  progressBar(id = "pbmod", value = 0, display_pct = TRUE, striped = TRUE)
)

server <- function(input, output, session) {

  observeEvent(session, {

    messages <- data.frame(c("Loading Environment...", "Parsing data...", "Preparing Live Data Feeds...", "Pondering what to display next...", "Calculating Llama Expectoration Trajectory...", "Breeding Fauna...",  "Charging Ozone Layer...", "Compressing Fish Files...", "Speculating Stock Market Indices...", "Application Ready!"), stringsAsFactors = FALSE)


    for (i in 1:10) {
      Sys.sleep(0.7)
      status <- messages[i,]
      status
      output$loadingtxt <- renderText(status)
      updateProgressBar(session = session, id = "pbmod", value = 100/10*i)
    }
  })
}

shinyApp(ui, server)

Upvotes: 0

Views: 404

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84709

Here is an option.

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  tags$h4(textOutput("loadingtxt")),
  progressBar(id = "pbmod", value = 0, display_pct = TRUE, striped = TRUE)
)

server <- function(input, output, session) {

  messages <- data.frame(c("Loading Environment...", "Parsing data...", "Preparing Live Data Feeds...", "Pondering what to display next...", "Calculating Llama Expectoration Trajectory...", "Breeding Fauna...",  "Charging Ozone Layer...", "Compressing Fish Files...", "Speculating Stock Market Indices...", "Application Ready!"), stringsAsFactors = FALSE)

  status <- reactiveVal()
  step <- reactiveVal()

  autoInvalidate <- reactiveTimer(700)

  i <- 0
  observe({
    autoInvalidate()
    i <<- i+1
    if(i == 9){ # stop the reactive timer
      autoInvalidate <<- reactiveTimer(Inf)
    }
    step(i)
    status(messages[i,])
  })

  output$loadingtxt <- renderText({
    updateProgressBar(session = session, id = "pbmod", value = 100/10*step())
    status()
  })
}

shinyApp(ui, server)

enter image description here

Upvotes: 1

Related Questions