首页 > 解决方案 > Shiny - 更新全局变量并在当前会话中查看结果

问题描述

我正在使用在时间 X 之后更新的全局变量。我遇到的这个问题是它更新了全局变量,但当前会话没有相应地更新,但是,任何新的会话打开都使用更新的全局变量。

问题:如何让当前会话使用更新后的全局变量?我认为将其包装在反应式中会起作用,但事实并非如此。

代码:

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)

如果您等待 30 多秒,然后打开一个新会话,您将看到数字已从 4 更改,但原始会话仍显示 4。它们应该显示相同的数字。

标签: shinyglobal-variablesshinydashboard

解决方案


解决了!意识到我需要将它包装在reactiveValuesvsreactive中。我还将值更新为数据框而不是单个数字,因为这符合我真正的仪表板的问题。

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)

推荐阅读