There are two ways in which a variable can be accessed across all server functions in a Shiny app.
One would be defining it inside the server, and then accessing it with <<- operator. It does not become shared across all sessions when doing so. Not being shared across all sessions is the intended behavior.
library(shiny)
ui <- fluidPage(
actionButton("btn", "Increase num"),
actionButton("msg", "Show num")
)
server <- function(input, output) {
n <- 0
observeEvent(input$btn, { n <<- n+1 } )
observeEvent(input$msg, { showModal(modalDialog(title=n, easyClose = T)) } )
}
shinyApp(ui = ui, server = server)
The other would be creating a reactive variable
library(shiny)
ui <- fluidPage(
actionButton("btn", "Increase num"),
actionButton("msg", "Show num")
)
server <- function(input, output) {
n <- reactiveVal(0)
observeEvent(input$btn, { n(n()+1) } )
observeEvent(input$msg, { showModal(modalDialog(title=n(), easyClose = T)) } )
}
shinyApp(ui = ui, server = server)
Which one would be better, and why?