Xavier Prudent
Xavier Prudent

Reputation: 1742

Use progressBar of R shiny within a function

Using progressbar in R shiny is quite straightforward when it comes within the server function :

library(shiny)
source(myFunctions.R)

shinyServer(function(input, output) {

withProgress(message = 'Chargement des données', value = 0, {
incProgress(0.5)
function1()
incProgress(0.6)
function2()
incProgress(0.7)
function3()
incProgress(0.8)
})
})

But what if I want to have them inside a function, for instance:

Allfunction <- function(){
withProgress(message = 'Chargement des données', value = 0, {
incProgress(0.5)
function1()
incProgress(0.6)
function2()
incProgress(0.7)
function3()
incProgress(0.8)
})
}

and hence

shinyServer(function(input, output) {
Allfunction()
})

Then I get

Warning: Error in withProgress: 'session' is not a ShinySession object.

and adding a session argument to the function, as advertised on a google forum did'nt do it.

Upvotes: 2

Views: 2064

Answers (1)

Florian
Florian

Reputation: 25435

Using withProgress() inside a function should not be a problem. Here is a working example. Note by the way that incProgress works cumulative, i.e. if you want to go from 0.5 to 0.6, you only have to add 0.1 as argument in the function.

Hope this helps!

library(shiny)

ui <- shinyUI(fluidPage(
  actionButton('click','click me!')

))

Allfunction <- function(){
  withProgress(message = 'Chargement des données', value = 0, {
    incProgress(0.5)
    function1()
    incProgress(0.1)
    function2()
    incProgress(0.1)
    function3()
    incProgress(0.1)
  })
}

function1 <- function(){Sys.sleep(1)}
function2 <- function1
function3 <- function1

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

  observeEvent(input$click, {
    Allfunction()
  })

}

shinyApp(ui, server)

Upvotes: 2

Related Questions