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.