How to listen for more than one event expression within a Shiny observeEvent

Kipras Kančys picture Kipras Kančys · Jan 31, 2017 · Viewed 14k times · Source

I want two different events to trigger an observer. It was suggested here that this should work. But it seems that it depends only on the second event.

observeEvent({ 
  input$spec_button
  mainplot.click$click
}, { ... } )

Have a look at the example.

ui <- shinyUI(bootstrapPage(
    actionButton("test1", "test1"),
    actionButton("test2", "test2"))
)

server <- shinyServer(function(input, output) {
    observeEvent({
        input$test1
        input$test2
    }, {
        print('Hello World')
    })
})

shinyApp(ui, server)

Once you click button test1 nothing happens. If you click button test2 it prints to your console. Once test2 button was pressed clicking test1 prints the message. That is a strange behaviour.

Another suggestion in that link was to use

list(input$test1, input$test2)

Which prints the message even without clicking the buttons.

Answer

Pork Chop picture Pork Chop · Jan 31, 2017

This should do it, note that you still have to check if the buttons were clicked as mentioned by @MrFlick

1. You can use reactive expression

#rm(list = ls())
library(shiny)
ui <- shinyUI(bootstrapPage(
  actionButton("test1", "test1"),
  actionButton("test2", "test2"))
)

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

  toListen <- reactive({
    list(input$test1,input$test2)
  })
  observeEvent(toListen(), {
    if(input$test1==0 && input$test2==0){
      return()
    }
    print('Hello World')
  })
})

shinyApp(ui, server)

2. As per example given by @MrFlick (now deleted)

#rm(list = ls())
library(shiny)
ui <- shinyUI(bootstrapPage(
  actionButton("test1", "test1"),
  actionButton("test2", "test2"))
)

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

  observeEvent(input$test1 | input$test2, {
    if(input$test1==0 && input$test2==0){
      return()
    }
    print('Hello World')
  })
})

shinyApp(ui, server)