reactiveValues vs reactive and eventReactive: a general question

Hi,

Consider the example below:

shinyApp(
  ui = fluidPage(
    numericInput("n", "n", 1),
    actionButton("go", "Click me to see the plot!"),
    plotOutput("plot")
  ),
  server = function(input, output, session) {
    
    output$plot <- renderPlot({
      if (input$go > 0) plot(head(cars, input$n))
      # or if (input$go) plot(head(cars, input$n))
    })
    
  }
)

Assume now that you are not allowed to use an actionButton but you want to show the plot 3 seconds after the shiny app started.

reactiveValues and reactiveVal are super useful to handle events such as setting a counter that can control whether to show outputs and when.

Below is the reactiveValues version but the reactiveVal would also do the job:

library(shiny)
library(shinyWidgets)

shinyApp(
  ui = fluidPage(
    numericInput("n", "n", 1),
    plotOutput("plot")
  ),
  server = function(input, output, session) {
    
    counter <- reactiveValues(value = 0)
    
    observe({
      counter$value <- isolate(counter$value) + 1
      invalidateLater(1000, session)
      if (counter$value == 3) {
        sendSweetAlert(
          session = session,
          title = "Success !!",
          text = "Now you can see the plot.",
          type = "success"
        )
      }
    })
    
    output$plot <- renderPlot({
      if (counter$value >= 3) plot(head(cars, input$n))
    })
    
  }
)

Don't forget the isolate in counter$value <- isolate(counter$value) + 1 to avoid updating the counter infinitely and crash your R session.

Here an example with more complex events: Shiny Contest Submission: Gotta Catch' Em (Almost) All. There are several reactiveValues examples in the pokeFight module.

2 Likes