InspectorSands
InspectorSands

Reputation: 2929

Calling shiny app as part of a function in R

The file app.R in my working directory contains a Shiny app:

shinyApp(
   ui = fluidPage(
    textInput("name", "Write your name", value = "stranger"),
    verbatimTextOutput("greeting")
  ),
  server = function(input, output) {
    output$greeting <- renderPrint({
      greeting <- paste("Hi,", input$name) 
      greeting
    })
  }
)

I want to call this app from within a function in R, then exit the app and have R execute the rest of the function. The function looks like this:

hi.app <- function() {
  library(shiny)
  shiny::runApp("app.R")
  print("Finished.")
}

The app opens upon running hi.app(), but when I close the app's window, the function calls the debugger:

Called from: Sys.sleep(0.001)

Desired behaviour:

  1. Run hi.app()
  2. Close app window
  3. print [1] "Finished"

Upvotes: 1

Views: 1098

Answers (1)

DoubleYou
DoubleYou

Reputation: 1087

I had the same issue, however, using a gadget is not required. The shinyApp function can still be used, including the stopApp function. The following example highlights both options:

  1. Adding a 'Done' button in the app to stop the app.
  2. Use the server session to catch the onSessionEnded.

Here is the code:

rm(list=ls())

library(shiny)

doshiny <- function() {
  app=shinyApp(
    ui = fluidPage(
      textInput("name", "Write your name", value = "stranger"),
      actionButton("ending","Done"),
      verbatimTextOutput("greeting")
    ),
    server = function(input, output, session) {
      output$greeting <- renderPrint({
        greeting <- paste("Hi,", input$name) 
        greeting
      })
      observeEvent(input$ending, {
        stopApp()
      })
      session$onSessionEnded(function() {
        stopApp()
      })
    }
  )
  runApp(app)
}

say_hi <- function() {
  doshiny()
  print("Finished.")
}

say_hi()

Upvotes: 2

Related Questions