Delay reactions with eventReactive()
Shiny's reactive programming framework is designed such that any changes to inputs automatically updates the outputs that depend on it. In some situations, we might want to explicitly control the trigger that causes the update.
The function eventReactive()
is used to compute a reactive value that only
updates in response to a specific event.
rval_x <- eventReactive(input$event, {
# calculations
})
This is a part of the course
“Building Web Applications with Shiny in R”
Exercise instructions
- Use
eventReactive()
to delay the execution of computing BMI until the user clicks on the button.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
ui <- fluidPage(
titlePanel('BMI Calculator'),
sidebarLayout(
sidebarPanel(
textInput('name', 'Enter your name'),
numericInput('height', 'Enter height (in m)', 1.5, 1, 2, step = 0.1),
numericInput('weight', 'Enter weight (in Kg)', 60, 45, 120),
actionButton("show_bmi", "Show BMI")
),
mainPanel(
textOutput("bmi")
)
)
)
server <- function(input, output, session) {
# MODIFY CODE BELOW: Use eventReactive to delay the execution of the
# calculation until the user clicks on the show_bmi button (Show BMI)
rval_bmi <- reactive({
input$weight/(input$height^2)
})
output$bmi <- renderText({
bmi <- rval_bmi()
paste("Hi", input$name, ". Your BMI is", round(bmi, 1))
})
}
shinyApp(ui = ui, server = server)
This exercise is part of the course
Building Web Applications with Shiny in R
Shiny is an R package that makes it easy to build interactive web apps directly in R, allowing your team to explore your data as dashboards or visualizations.
In this chapter, you will learn about reactive programming. You will learn about reactive sources, conductors and endpoints and how they come together to drive the magic behind Shiny. You will also learn how to utilize your understanding of reactivity to build performant Shiny apps.
Exercise 1: Reactivity 101Exercise 2: Source vs. Conductor vs. EndpointExercise 3: Add a reactive expressionExercise 4: Understanding reactive expressionsExercise 5: Observers vs. reactivesExercise 6: Add another reactive expressionExercise 7: Does this have a side effect?Exercise 8: Add an observer to display notificationsExercise 9: Stop - delay - triggerExercise 10: Stop reactions with isolate()Exercise 11: Delay reactions with eventReactive()Exercise 12: Trigger reactions with observeEvent()Exercise 13: Controlling action triggersExercise 14: Applying reactivity conceptsExercise 15: Reactivity concepts: observe & reactiveExercise 16: Convert height from inches to centimetersWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.