Atrasar reações com eventReactive()
A estrutura de programação reativa do Shiny foi projetada para que quaisquer mudanças nos inputs atualizem automaticamente as saídas que dependem deles. Em algumas situações, podemos querer controlar explicitamente o gatilho que causa a atualização.
A função eventReactive() é usada para calcular um valor reativo que só
atualiza em resposta a um evento específico.
rval_x <- eventReactive(input$event, {
# cálculos
})
Este exercício faz parte do curso
Construindo Aplicações Web com Shiny em R
Instruções do exercício
- Use
eventReactive()para atrasar a execução do cálculo do IMC até que a pessoa usuária clique no botão.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
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)