mrip
mrip

Reputation: 15163

How to exit a Shiny app and return a value

The help page for runApp says:

Runs a Shiny application. This function normally does not return; interrupt R to stop the application (usually by pressing Ctrl+C or Esc).

Does "normally" mean "always"? Is there any way to add an "exit" button and return a value to the R session that called runApp? Even if it's a hack, this would be convenient functionality. I've tried some searching but haven't found anything. I've also looked at the source for runApp, the last line is return(.globals$retval), so it looks like there should be a way.

Can I set .globals$retval directly and then call some kind of interrupt? Is there a function in the shiny package that does this?

Upvotes: 20

Views: 8364

Answers (1)

jdharrison
jdharrison

Reputation: 30445

There is a stopApp function that stops the running app and returns an optional value:

myValue <- runApp(list(
  ui = bootstrapPage(
    numericInput('n', 'Number of obs', 100),
    actionButton("myBtn", "Press ME!"),
    plotOutput('plot')
  ),
  server = function(input, output, session) {
    output$plot <- renderPlot({ hist(runif(input$n)) });
    observe({
      if(input$myBtn > 0){
        stopApp(7)
    }
    })
  }
))

On stopping:

> myValue
[1] 7

Upvotes: 22

Related Questions