Differences between observeEvent and eventReactive

Hi,

They are identical but for one thing:

  • observeEvent() just executes code within it's boundaries but does not assign the output to anything
  • eventReactive() will save the output to a reactive variable

Both of them will only execute code code if the condition at the top is satisfied. That's where they differ from reactive() that will run anytime any of the reactive values within change.

So you use observeEvent with code that does not produce an output that you capture in a reactive variable, and eventReactive when you do. On the other hand, you can simulate the effect of one with the other.

EXAMPLE

observeEvent(input$button1, {
 showModal(modalDialog("You clicked the button!"))
})

EXAMPLE

myVar = eventReactive(input$button1, {
  Sys.time()
})

output$myText = renderText({
  paste("You clicked the button at", myVar())
})

This is the longer version with observeEvent instead of eventReactive

clickTime = reactiveVal()
observeEvent(input$button1, {
  clickTime(Sys.time())
})

output$myText = renderText({
  paste("You clicked the button at", clickTime())
})

Hope this helps,
PJ

1 Like