It is possible to execute some code R on ending the session of a Shiny app with the help of session$onSessionEnded. However, there's an issue if we use that to execute some code which runs a Shiny app. Here is an example:
library(shiny)
library(miniUI)
myGadget <- function() {
ui <- miniPage(
gadgetTitleBar("My Gadget")
)
server <- function(input, output, session) {
observeEvent(input$done, {
session$onSessionEnded(function() {
myGadget()
})
stopApp()
})
observeEvent(input$cancel, {
stopApp()
})
}
runGadget(ui, server, stopOnCancel = FALSE)
}
Run myGadget() and click on the 'Done' button in the app. Then the gadget stops and it is launched again, but then the RStudio console is not locked as it should be, and there's no button to stop the app.
A solution for an app running in RStudio is to use rstudioapi::sendToConsole to send the code to the RStudio console. But not everybody uses RStudio, so I'm looking for a cross-IDE solution.