How to gracefully exit a Shiny app

,

Having developed a number of Shiny apps on RStudio Server and Connect over a number of years, I was embarrassed to learn that my inclusion of stopApp and onStop to close connections was closing the app for all concurrent users. What is the correct way to close database connections and the browser for current session but not affect other innocent bystanders?

First of all, you should understand that onStop() really has two similar behaviours. If you place it inside a shiny server function, it will be called when the current user session is ended. If you place it outside the shiny app, then it will only be called once when the app itself is shut down - not once per user.

With that in mind, you really have two questions here: how to deal with database connections, and how to close the browser.

For the database connections: if you're using {pool}, you likely don't need to do anything. The pool package is meant to take care of the connections. But if you want to be more explicit and safer, you can manually call pool::poolClose()when the app shuts down, but make sure to only call it inside of the app-level onStop(), and not inside a server-level onStop(). If you're using a database connection, then if it's a global connection, you again want to only close it when the entire app shuts down, but if it's a per-session connection then it can be closed in the session's onStop.

If you want to kill the current user session without killing the others, you can use session$close().

1 Like

Thanks for the explanation. It’s now clear that my former approach was causing problems for other concurrent users, but I believe my new approach will work:

  • DB connection at the global level
  • onStop function closing the connection at the global level
  • ‘Exit’ actionButton within the server function calling session$close