Reputation: 794
I do have a bit of code executed within session$onSessionEnded()
(such as a DBI::dbDisconnect()
) of a Shiny app and I wonder the best practice to trigger it directly from the R code (for instance when a condition is not met, you close the app but also want to trigger this bit of code).
stop()
will stop the R code (but not the app itself letting a "ghost" app) whereas stopApp()
will close the app without triggering the session$onSessionEnded()
Should I for instance create a function that I should call before stopApp()
ing or is there a way to tell to the application to trigger the session$onSessionEnded()
? Like a session$endSession()
?
Upvotes: 4
Views: 775
Reputation: 33550
You can call session$close()
from anywhere within the server function to stop the current session.
Here is an example:
library(shiny)
ui <- fluidPage(
actionButton("stopSession", "Stop session")
)
server <- function(input, output, session) {
session$onSessionEnded(function(){
cat(sprintf("Session %s was closed\n", session$token))
})
observeEvent(input$stopSession, {
cat(sprintf("Closing session %s\n", session$token))
session$close()
})
}
shinyApp(
ui,
server,
onStart = function() {
cat("Doing application setup\n")
onStop(function() {
cat("Doing application cleanup\n")
})
}
)
Upvotes: 2