mchen mchen - 2 months ago 14
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)
shinyServer(
... # things involving db
)


Now, how to ensure that the connection
db
is closed properly (via
dbDisconnect(db)
) 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

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() {
    dbDisconnect(db)
})

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

Comments