Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger session$onSessionEnded in R Shiny using code?

Tags:

r

shiny

I do have a bit of code executed within session$onSessionEnded() (such as a DBI::dbDisconnect()) of a Shiny app and I wonder the best practice to trigger it directly from the R code (for instance when a condition is not met, you close the app but also want to trigger this bit of code).

stop() will stop the R code (but not the app itself letting a "ghost" app) whereas stopApp() will close the app without triggering the session$onSessionEnded()

Should I for instance create a function that I should call before stopApp()ing or is there a way to tell to the application to trigger the session$onSessionEnded()? Like a session$endSession()?

like image 325
yeahman269 Avatar asked Sep 07 '25 21:09

yeahman269


1 Answers

You can call session$close() from anywhere within the server function to stop the current session.

Here is an example:

library(shiny)

ui <- fluidPage(
  actionButton("stopSession", "Stop session")
)

server <- function(input, output, session) {
  
  session$onSessionEnded(function(){
    cat(sprintf("Session %s was closed\n", session$token))
  })
  
  observeEvent(input$stopSession, {
    cat(sprintf("Closing session %s\n", session$token))
    session$close()
  })
}

shinyApp(
  ui,
  server,
  onStart = function() {
    cat("Doing application setup\n")
    onStop(function() {
      cat("Doing application cleanup\n")
    })
  }
)
like image 130
ismirsehregal Avatar answered Sep 10 '25 08:09

ismirsehregal