简体   繁体   中英

Unexpected reactivity while using multiple reactiveVal in Shiny

I am experiencing unexpected behavior while using multiple reactiveVal's in Shiny. I am aware of the existence of reactiveValues, which will likely solve my problem, but I would still like to find out why this behavior is occuring. In the code below, I have two reactiveVals:

  • reval1 , which is updated every second
  • reval2 , which never changes value.

my_plot is only dependent on reval2. Therefore I would expect it to never invalidate. However, the plot changes every second. In the documentation , I don't see any mention of the impossibility of using two reactiveVal's. Am I misinterpreting or overlooking something?


server <- function(input, output, session) {

  set.seed(1)
  reval1<- reactiveVal(runif(1)) # useful
  reval2 <- reactiveVal(runif(1)) # useless

  # update reval1 every second
  autoInvalidate <- reactiveTimer(intervalMs = 1000, session = session) 
  observeEvent(autoInvalidate(),{
    reval1(reval1()+1)
  })

  # plot is only dependent on reval2.
  output$my_plot<- renderPlot({
    a<- reval2()
    df= data.frame(x=runif(10),y=runif(10))
    plot(df$x,df$y)
  })

}

ui <- shinyUI(
  fluidPage(
    plotOutput("my_plot")
  )
)

shinyApp(ui,server)

This is a known issue. and should be fixed in the new version of shiny. There are already fixes implemented in the dev version. Note I haven't tested it myself...

https://github.com/rstudio/shiny/pull/1712

https://github.com/rstudio/shiny/issues/1710

This is really interesting, I would even submit a bug in this case. I tried to re-write that as

server <- function(input, output, session) {

  set.seed(1)
  reval1 <- reactiveVal(runif(1)) # useful
  reval2 <- reactiveVal(runif(1)) # useless

  # update reval1 every second
  autoInvalidate <- reactiveTimer(intervalMs = 1000) 
  observe({
    autoInvalidate()
    reval1(reval1() + 1)
    print(reval1())
  })

  # plot is only dependent on reval2.
  output$my_plot<- renderPlot({
    a <- reval2()
    df <- data.frame(x=runif(10),y=runif(10))
    plot(df$x, df$y)
  })

}

An put it some browsers and in this, the plot does not even render. Also you can see that during the runtime the observe() and output$my_plot get fired in a loop and consistently with much shorter time than 1000ms! By the way this is the reactivity plot:

反应性图

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