1

I found out a behavior that is at least confusing in Shiny, and I would like to figure out why it occurs.

I have a Shiny app with just a selectInput input that allows the selection of multiple values (multiple = TRUE) and two observers that listen to changes in the input variable: one that uses observeEvent directly on the input variable and one that uses just observe with the input variable inside its body.

The weirdness occurs when, in the multiple options, one removes all of the options in the selector. In that case, only the observe block of code executes and the observeEvent does not.

Why does Shiny do that? Should it work like that?

A minimal working example (you just need to deselect all of the variables):

library(shiny)

ui <- fluidPage(
    selectInput("select", 
                label = "Multiple choices",
                choices = c(1, 2, 3, 4),
                selected = c(1, 2), 
                multiple = TRUE)
)

server <- function(input, output) {
    # Won't execute with no value selected
    observeEvent(input$select, {
        vec_str <- paste(input$select, collapse = " ")
        print(paste("observeEvent:", vec_str))
    })
    
    # Will execute with no value selected
    observe({
        vec_str <- paste(input$select, collapse = " ")
        print(paste("observe:", vec_str))
    })
}

shinyApp(ui = ui, server = server)

Thanks in advance :)

1 Answer 1

1

There is a setting in observeEvent that allows you to ignore the case when is.null(input$select). Set the argument ignoreNULL = FALSE and you get the result you want.

library(shiny)

ui <- fluidPage(
  selectInput("select", 
              label = "Multiple choices",
              choices = c(1, 2, 3, 4),
              selected = c(1, 2), 
              multiple = TRUE)
)

server <- function(input, output) {
   # executes even when input$select is NULL
  observeEvent(input$select, {
    vec_str <- paste(input$select, collapse = " ")
    print(paste("observeEvent:", vec_str))
  }, ignoreNULL = FALSE)
  
  # Will execute with no value selected
  observe({
    vec_str <- paste(input$select, collapse = " ")
    print(paste("observe:", vec_str))
  })
}

shinyApp(ui = ui, server = server)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for taking the time and effort to respond to the post. I wasn't aware that was the default behavior of the observeEvent function. Greatly appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.