Kevin
Kevin

Reputation: 2054

Shiny - Updating global variable and seeing the result in current session

I am working with global variables that update after time X. This issue I am coming across is it updates the global variable but the current session doesn't update accordingly, however, any new session open uses the updated global variable.

Question: how do I get the current session to use the updated global variable? I thought wrapping it in a reactive would work but it doesn't.

Code:

library(shiny)
library(shinydashboard)

####/GLOBAL/####
num <- 4

####/UI/####
header <- dashboardHeader()

sidebar <- dashboardSidebar()

body <- dashboardBody(
  verbatimTextOutput("test")
)

ui <- dashboardPage(header, sidebar, body)

####/SERVER/####
server <- function(input, output, session) {

  data <- reactive({num})
  output$test <- renderText({ data() })

  observe({
    invalidateLater(0.5*60*1000,session)

    num <<- sample(1:1000,1,replace=T)
  })

}

shinyApp(ui, server)

If you wait 30+ seconds and then open up a new session you will see that the number has changed from 4 but the original session still shows 4. They should be showing the same number.

Upvotes: 2

Views: 1374

Answers (1)

Kevin
Kevin

Reputation: 2054

Solved! Realized I needed to wrap it in a reactiveValues versus reactive. I also made the updating a value a dataframe versus a single number because that fits my real dashboard's problem.

library(shiny)
library(shinydashboard)

####/GLOBAL/####
dataset <- data.frame(ColA = c("dogs", "cats", "birds"), ColB = c(10, 2, 2), stringsAsFactors = FALSE)

####/UI/####
header <- dashboardHeader()

sidebar <- dashboardSidebar()

body <- dashboardBody(
  box(width = 3, tableOutput("test"))
)

ui <- dashboardPage(header, sidebar, body)

####/SERVER/####
server <- function(input, output, session) {

  values <- reactiveValues(n = dataset)

  data <- reactive({values$n})
  output$test <- renderTable({ data() })

  observe({
    invalidateLater(0.5*60*1000,session)

    new1 <- sample(1:10,1,replace=T)
    new2 <- sample(1:10,1,replace=T)
    new3 <- sample(1:10,1,replace=T)

    print(new1)
    print(new2)
    print(new3)

    dat <- data.frame(ColA = c("dogs", "cats", "birds"), ColB = c(new1, new2, new3), stringsAsFactors = FALSE)

    values$n <- dat
    dataset <<- dat

  })

}

shinyApp(ui, server)

Upvotes: 1

Related Questions