Elmahy
Elmahy

Reputation: 402

How to render something first in shiny before excuting the rest of code?

I want to render a text to notify the user that a task is going to run, but it seems that shiny executes all code in server first then it moves to UI. Here is an example:

library(shiny)

ui <- fluidPage(
  mainPanel(
         textOutput("ptext")
      ))

server <- function(input, output) {
   output$ptext <- renderText("creating a dataframe")
   df <- matrix(rnorm(10000),nrow = 10) # a large dataset
   output$ptext <- renderText("dataframe created !!")
   }

shinyApp(ui = ui, server = server)

In the above example, I never see "creating a dataframe", How to render that text first before executing the rest of the code.

Upvotes: 0

Views: 670

Answers (1)

r2evans
r2evans

Reputation: 160407

It's not the most beautiful, but if you can use an input for status messages like this, you can relay what's going on ...

library(shiny)

ui <- fluidPage(
  mainPanel(
    textInput("notice", "Status", "creating a dataframe"),
    textOutput("ptext")
  )
)

server <- function(input, output, session) {
  dat <- reactive({
    Sys.sleep(3)
    matrix(rnorm(10000), nrow = 10)
  })

  output$ptext <- renderText({
    req(dat())
    updateTextInput(session, "notice", value = "dataframe created !!")
    return("hello world")
  })
}

shinyApp(ui = ui, server = server)

(Note the addition of session to the arguments to server, necessary to use updateTextInput(session, ...).)

You could get more complex by using dynamic UI creation and deletion, or object hiding (perhaps using shinyjs), but that is getting a bit more complex than I think you may want.

Upvotes: 1

Related Questions