Declaring a Shiny variable in the scope of the server function

When declaring a variable from an observeEvent function of the server using <<- it is declared as a global variable and becomes available to all users of the app. How should one declare a variable from an observeEvent that would be accessible to other observeEvent functions, but not to other users of the app?

Using the following code, when I open two sessions of the app (with Shiny Server) the generated value is shared across both sessions.

library(shiny)

ui <- fluidPage(
  actionButton("btn1", "generate a value"),
  actionButton("btn2", "show a value")
)

server <- function(input, output, session) {
  observeEvent(input$btn1, myvalue <<- runif(n=1) )
  observeEvent(input$btn2, showModal(modalDialog(myvalue)))
}

shinyApp(ui, server)
library(shiny)

ui <- fluidPage(
  actionButton("btn1", "generate a value"),
  actionButton("btn2", "show a value")
)

server <- function(input, output, session) {
  myvalue <- eventReactive(input$btn1,  
                           runif(n=1) )
  observeEvent(input$btn2, showModal(modalDialog(req(myvalue()))))
}

shinyApp(ui, server)

I agree that your way is the correct and recommended way that code should be written in Shiny. However, I'd like to understand how it is possible to achieve the goal of the OP without using reactive values. That would give me a better understanding how Shiny scoping works.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.