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 :)
question from:
https://stackoverflow.com/questions/65924161/why-does-observe-and-observeevent-behave-differently-on-change-of-input-vari 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…