mchen mchen - 1 year ago 162
R Question

How to implement a cleanup routine in R Shiny?

For instance, my shiny app might open a DB connection

# server.R
db <- dbConnect("SQLite", DB_PATH)
... # things involving db

Now, how to ensure that the connection
is closed properly (via
) when the Shiny session ends? Indeed, should cleanup be performed for each client that connects to the server, or just once?

I simply fear that with multiple users connecting and disconnecting to the Shiny app all the time, they'll leave dangling DB connections if not properly cleaned up. Indeed, clients may disconnect without warning simply by closing their browsers.

Answer Source

The correct way to do this is to assign a function that performs your clean-up with session$onSessionEnded. For example, in server.R:

cancel.onSessionEnded <- session$onSessionEnded(function() {

You can then call cancel.onSessionEnded to undo the assignment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download