raistlin raistlin - 4 months ago 12
R Question

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"


Answer

UPDATE: the trick was to use a shiny gadget instead of a shiny app (more details can be found here):

hi_gadget <- function() {
  ui = miniPage(
    gadgetTitleBar("My Gadget"),
    textInput("name", "Write your name", value = "stranger"),
    verbatimTextOutput("greeting")
  )
  server = function(input, output) {
    output$greeting <- renderPrint({
      greeting <- paste("Hi,", input$name) 
      greeting
    })
    observeEvent(input$done, {
      stopApp()
    })
  }
  runGadget(ui, server)
}

say_hi <- function() {
  library(shiny)
  library(miniUI)
  hi_gadget()
  print("Finished.")
}

The gadget is interrupted via the Done button and the function continues to execute.