简体   繁体   中英

R - Shiny - How to update a textOutput multiple times in an observer

I have a question about updating a text output in a shiny app.

In an observer, I make several computations, and, between each of them, I want to show informations in a text output.

I tried several things, but the only thing it is showing is the last information :

library(shiny)

ui <- fluidPage(
  headerPanel("Hello !"),
  mainPanel(
    actionButton("bouton", "Clic !"),
    textOutput("texte")
  )
)

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

  observeEvent(input$bouton, {
    output$texte = renderText("Initialization...")
    Sys.sleep(1)
    output$texte = renderText("Almost ready...")
    Sys.sleep(3)
    output$texte = renderText("Ok !")
  })
}

runApp(list(ui=ui,server=server), launch.browser = TRUE)

Or :

library(shiny)

ui <- fluidPage(
  headerPanel("Hello !"),
  mainPanel(
    actionButton("bouton", "Clic !"),
    textOutput("texte")
  )
)

server <- function(input,output, session){
  rv = reactiveValues()

  rv$mess = ""

  observeEvent(input$bouton, {
    rv$mess = "Initialization..."
    Sys.sleep(1)
    rv$mess = "Almost ready..."
    Sys.sleep(3)
    rv$mess = "Ok !"
  })
  observe({
    output$texte <<- renderText(rv$mess)
  })
}

runApp(list(ui=ui,server=server))

Edit : in these two examples, it shows nothing until the last message "OK !"

Where am I wrong ?

Thanks for your help !

Thanks to Eugene, this is my working piece of code (server only) :

server <- function(input,output, session){
  rv = reactiveValues()

  rv$mess = ""

  observeEvent(input$bouton, {
    withProgress({
      setProgress(message = "Initialization...")
      Sys.sleep(1)
      setProgress(message = "Almost ready...")
      Sys.sleep(3)
      setProgress(message = "Ok !")
      Sys.sleep(2)
    })
  })
}

You might consider achieving this with shiny's progress indicators by:

  1. wrapping everything in your observer in withProgress , and
  2. using setProgress( message = "some message" ) where you use rv$mess and output$texte

However, the progress indicator will show up in the top-right (or elsewhere if you modify the css) and not in your output box.

http://shiny.rstudio.com/articles/progress.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM