Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a cleanup routine in R Shiny?

Tags:

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.

like image 839
mchen Avatar asked Apr 24 '14 18:04

mchen


People also ask

Is R shiny difficult to learn?

Along with Shiny elements, you can use HTML elements to stylize your content in your application. In my opinion, R Shiny is very easy to learn despite how powerful the tool is. If you're working on a side project or looking to add something to your portfolio, I highly recommend trying it out.

How do I run a shiny code in R?

Open the app. R script in your RStudio editor. RStudio will recognize the Shiny script and provide a Run App button (at the top of the editor). Either click this button to launch your app or use the keyboard shortcut: Command+Shift+Enter (Control+Shift+Enter on Windows).

Is R shiny useful?

All in all, Shiny is an extremely helpful software package that doesn't only help to communicate research results or facts and concepts in science (for example as a tool for teaching). As shown with our application, it may also help to bridge the gap between an R and non-R audience for your existing R package.


1 Answers

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.

like image 63
Matthew Plourde Avatar answered Oct 01 '22 19:10

Matthew Plourde