Woody
Woody

Reputation: 612

How to render text to output without waiting for function to finish?

I am new to Shiny coding, and I am writing code to implement image processing and calculation. However, I am having a problem as the output text is displayed only when the function has finish executed.

The following is the part of code I have:

server.R

shinyServer(function(input, output) {
    for(i in 1:100){
        processImage(i);
        output$console <- renderText({
            paste(i," images completed");
        })
    }

    processImage(i) <- function (){
        # code goes here
    }
}

ui.R

shinyUI(fluidPage(
    titlePanel(
        h4("Image Processing")
    ),
    sidebarLayout(
        sidebarPanel(
            # some inputs here
        ),
        mainPanel(
            textOutput('console')
        )
    )
))

output$console is not rendered until the for loop is finished. I have search the Internet for the solution, but found none. Can anyone help me with this?

Upvotes: 1

Views: 841

Answers (1)

Pork Chop
Pork Chop

Reputation: 29387

You can do something like this with withProgress. Edit: You need to install shinyIncubator package

rm(list = ls())
library(shiny)
library(shinyIncubator)

server <- function(input, output, session) {
  observe({
    if(input$aButton==0) return(NULL)
    withProgress(session, min=1, max=15, expr={
      for(i in 1:10) {
        setProgress(message = 'Processing...',detail = paste0('Image number ',i))
        Sys.sleep(0.5)
      }
    })
  })
}

ui <- pageWithSidebar(
  headerPanel("Testing"),
  sidebarPanel(actionButton("aButton", "Let's go!"), width=2),

  mainPanel(progressInit())
)

shinyApp(ui = ui, server = server)

enter image description here

Upvotes: 1

Related Questions