简体   繁体   中英

Modify and Read Global variable after session in R Shiny

I am trying to read a global variable which is declared before UI. In a scenario I am modifying the global variable during the session and in observer function. But when I want to print that modified variable after session kill, it prints old values itself. I want to keep this modified variable(in my requirement every time it changes on each session) for each session.

library(shiny)    

timeoutSeconds <- 5
varA <- 3 #Declaring Global variable    

#Trigger the function after the 5 seconds 
inactivity <- sprintf("
function idleTimer() {
var t = setTimeout(logout, %s);
window.onmousemove = resetTimer; // catches mouse movements
window.onmousedown = resetTimer; // catches mouse movements
window.onclick = resetTimer;     // catches mouse clicks
window.onscroll = resetTimer;    // catches scrolling
window.onkeypress = resetTimer;  //catches keyboard actions

function logout() {
   Shiny.setInputValue('timeOut', '%ss')
  }

function resetTimer() {
   clearTimeout(t);
   t = setTimeout(logout, %s);  // time is in milliseconds (1000 is 1 second)
   }
}
idleTimer();", 
timeoutSeconds*1000, 
timeoutSeconds, 
timeoutSeconds*1000)

#UI 
ui <- fluidPage(
  tags$script(inactivity)  

)

#Server
server <- shinyServer(function(input,output,session){


  observeEvent(input$timeOut, {
    varA <-varA + 1 #Modifing this global variable for each session

    print(paste0("Session (", session$token, ") timed out at: ", Sys.time()))
    showModal(modalDialog(
      title = "Timeout",
      paste("Session timeout due to", input$timeOut, "inactivity -", Sys.time()),
      footer = NULL
    ))
    session$close()
  })

  session$onSessionEnded(function() {

    #Should print 4
    print(varA) #Printing the modified  variable  during sessions

  })

})

runApp(ui,server)

I want to print 4 in the above code. I have tried multiple times, but may be it doesn't work like that. can you please help me anyone on this.

print(varA) is outside the observeEvent function so it will print the initial value of varA (which is 3) and not the updated value (4). The solution is to put print(varA) just below session$close() in the observeEvent function.

That means you can remove the (now empty) session$onSessionEnded(function() { }) function.

Try this:

varA <<-varA + 1

To change the global variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM