I have a shiny application in which I am making some connections to databases and other components. I wish to close these connections when the app is brought down. Is there a way to execute a function when the shiny app is closed?
-
Take a look at `?on.exit` - this may help. – Andrie Jul 16 '14 at 11:08
-
1Look at `session$onSessionEnded` documented in `?session` in the latest release of `shiny` – jdharrison Jul 16 '14 at 12:22
2 Answers
As mentioned in the comments by @jdharrison you can us session$onSessionEnded in the shiny server.
This extremely simple example will print a message to the console when you close the app, but you can replace that print statement with some statements that close the database connections.
library(shiny)
ui <- fluidPage(
#Empty UI
)
server <- function(input, output,session) {
session$onSessionEnded(function() {
print('hello, the session has ended')
})
}
shinyApp(ui = ui, server = server)

- 1,304
- 1
- 13
- 26
As has been previously said, you can perform an action at the conclusion of a session by using session$onSessionEnded
. This would work if you make one database connection for each user session, but often you might instead be sharing one database connection between multiple users. In that case you need run code when the server function terminates. This can be done using the onStop()
function (https://shiny.rstudio.com/reference/shiny/latest/onStop.html). Example from the documentation:
library(shiny)
shinyApp(
ui = basicPage("onStop demo"),
server = function(input, output, session) {
onStop(function() cat("Session stopped\n"))
},
onStart = function() {
cat("Doing application setup\n")
onStop(function() {
cat("Doing application cleanup\n")
})
}
)

- 873
- 1
- 8
- 12