简体   繁体   中英

Shiny Reactivity Explaination (using ObserveEvent)

I am hoping to get some clarity on Shiny's reactivity behavior using the simplified code below as example.

When y is updated in the app, the graph updates.
When x is updated in the app, the graph does NOT update.

I have read Shiny's tutorials and my understanding is that given that I have wrapped both test() and plot() functions in observeEvent, both parameters should not cause the graph to update when changed.

Can someone help explain the logic behind this?

library(shiny)

test <- function(x){x*2}

shinyServer(function(input, output, session) {

  observeEvent(input$run, {
    x = test(input$x)
    output$distPlot <- renderPlot({
      if(input$y){
        x = x+2
      }
      plot(x)
    })
  })

})

shinyUI(fluidPage(

  sidebarLayout(
      sidebarPanel(
      numericInput("x", "x:", 10),
      checkboxInput("y", label = "y", value = FALSE),
      actionButton("run", "run")
    ),

    mainPanel(
      plotOutput("distPlot")
    )
  )
))

If you put the line x = test(input$x) inside of the renderPlot it will react when either x or y changes. Essentially the observer creates a reactive output when the action button is clicked the first time, then you simply have a reactive element that responds to changes to inputs inside of it. Hope that helps.

To make it so the graph only updates when the button is clicked, you will probably need to put the data that is being graphed in a eventReactive and use that as the input for the graph.

Something like this:

data <- eventReactive(input$run, {
    x = test(input$x)
    if(input$y){
      x = x+2
    }
    x
  })
output$distPlot <- renderPlot({
  plot(data())
})

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