4

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?

Avinash
  • 2,521
  • 4
  • 21
  • 35

2 Answers2

6

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)
aeongrail
  • 1,304
  • 1
  • 13
  • 26
5

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")
    })
  }
)
Peter Harrison
  • 873
  • 1
  • 8
  • 12