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

前端 未结 2 1749
谎友^
谎友^ 2020-12-09 04:54

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.

obser         


        
相关标签:
2条回答
  • 2020-12-09 05:29

    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)
    
    0 讨论(0)
  • 2020-12-09 05:43

    observeEvent is a wrapper for complex observe cases. In this particular case of an action when one or other reactive value changes, one could use a simple observe. This works:

    require(shiny)    
    ui <- basicPage(
          actionButton("test1", "test1"),
          actionButton("test2", "test2")
        )
        
        server <- function(input, output, session){
        
          observe( {
            input$test1
            input$test2
            if(input$test1==0 && input$test2==0){
              return()
            }
            print('Hello World')
            })
        }
        
        shinyApp(ui, server)
    

    There is a point in using observeEvent with options to eliminate the return() call:

    ui <- basicPage(
      actionButton("test1", "test1"),
      actionButton("test2", "test2")
    )
    
    server <- function(input, output, session){
    
      observeEvent(input$test1 | input$test2, { print('Hello World') } , ignoreInit = TRUE)
    }
    
    shinyApp(ui, server)
    
    0 讨论(0)
提交回复
热议问题