How one should check whether or not the validate(need())
conditions are fulfilled in a reactive expression?
Trying to get access to a reactive expression when this one does not fulfill the conditions lead to a silent error and stops the function/observer whatever stored the initial call. While this makes perfect sense from an UI perspective, how to handle it from a function perspective and prevent a premature stop?
Below an example (based on the genuine Shiny Validate tutorial) which replicates this behavior: until you select a value in the selectInput()
, you will not see the console message "This message will only be printed when data() validate/need are fulfilled." when clicking the button because the observeEvent()
is stopped. In the meantime, you may still be eager to do something, like writing an empty file or triggering something at this point, etc.
require(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("data", label = "Data set",
choices = c("", "mtcars", "faithful", "iris"))
),
mainPanel(
actionButton(inputId = "actbtn", label = "Print in console reactive value")
)
)
)
server <- function(input, output) {
data <- reactive({
validate(
need(input$data != "", "Please select a data set"),
need(input$data %in% c("mtcars", "faithful", "iris"),
"Unrecognized data set"),
need(input$data, "Input is an empty string"),
need(!is.null(input$data),
"Input is not an empty string, it is NULL")
)
get(input$data, 'package:datasets')
})
observeEvent(input$actbtn, {
print(data())
print("This message will only be printed when data() validate/need are fulfilled.")
})
}
shinyApp(ui, server)
I tried to check the "state" of the reactive expression prior to actually calling it, without success for now. I can of course adapt my app (for instance by doing a validation-like by myself or just re-performing the conditions prior to calling the reactive expression) but I am quite confident that there is a smarter way to handle this context.