How to detect if in a Shiny session? Or: How to use withProgress outside of Shiny? [reprex]

I want to make a simple function that implements withProgress if the code is being executed in Shiny, but does not implement withProgress otherwise (just runs the function). Minimal reprex:

#This simple function works in a Shiny app:

#Function that implements a dummy progress bar, and appends "_abc" to a string
myfunc <- function(sometext){ #A string in quotes
  withProgress(message = 'Fake Timer', value=0, {
                 for (i in 1:3) {
                   incProgress(1/3)
                   Sys.sleep(0.25)
                 }
               })
  print(paste0(sometext, "_abc"))
}


library(shiny)

#Simple shiny app that runs 'myfunc' on a textInput
ui <- fluidPage(
 textInput(inputId = "mytextinput",
           label="Type Here"),
 textOutput("myresult"))


server <- function(input, output, session) {
  
    output$myresult <- renderText({
      req(input$mytextinput)
      myfunc(input$mytextinput)
      })

}
shinyApp(ui, server) #run app

But if running outside of Shiny, we get the error due to withProgress needing to run in Shiny:

> myfunc("mytext")

Error in withProgress(message = "Fake Timer", value = 0, { :
'session' is not a ShinySession object.

I've tried sticking 2 versions of the function in an if statement (one using withProgress, one not), with the condition interactive(), but that doesn't seem to apply to the command line/non-Shiny sessions either.

shiny::isRunning()

This function tests whether a Shiny application is currently running.

TRUE if a Shiny application is currently running. Otherwise, FALSE.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.