Dynamically created UI items trigger event observers upon app initialisation. This might an undesirable behaviour in some instances. To avoid this, event observers compare current with previous state of the UI item. Only if a value has changed, further action is triggered. Upon app initialisation the values returned by input
are equal to the default value within rv
. Thus, no action is taken. Find below a minimal example. There might be more elegant solutions out there.
library(shiny)
library(rlang)
ui <- fluidPage(
uiOutput("body"),
textOutput("text")
)
server <- function(input, output, session) {
# Initial state
items <- list(dynamicBox = FALSE, slider = 5L) # "5L" !important
# Default values (dynamic, not necessary in this example)
rv <- exec(reactiveValues, !!!items)
# Render UI
output$body <- renderUI(
tagList(
checkboxInput("dynamicBox", "dynamicBox"),
sliderInput("slider", value = 5L, min = 0L, max = 10L, step = 1L, label = "Slider")
))
# Build event observers in a loop
sapply(names(items), function(i){
observeEvent(input[[i]], {
# Compare current with previous state
if(!identical(rv[[i]], input[[i]])){
output$text <- renderText({sprintf("Observer of %s is executed. Value = %s", i, isolate(input[[i]]))})
}
rv[[i]] <- input[[i]]
})
})
}
shinyApp(ui, server)
Created on 2020-02-18 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)</sup>