开始使用免费开始使用

Stop reactions with isolate()

Ordinarily, the simple act of reading a reactive value is sufficient to set up a relationship, where a change to the reactive value will cause the calling expression to re-execute. The isolate() function allows an expression to read a reactive value without triggering re-execution when its value changes.

In this exercise, you will use the isolate() function to stop reactive flow.

本练习是课程的一部分

Building Web Applications with Shiny in R

查看课程

练习说明

  • Update the server code so that the text output updates only when user changes the height or weight, and NOT the name.

交互式实操练习

通过完成这段示例代码来试试这个练习。

ui <- fluidPage(
  titlePanel('BMI Calculator'),
  sidebarLayout(
    sidebarPanel(
      textInput('name', 'Enter your name'),
      numericInput('height', 'Enter your height (in m)', 1.5, 1, 2, step = 0.1),
      numericInput('weight', 'Enter your weight (in Kg)', 60, 45, 120)
    ),
    mainPanel(
      textOutput("bmi")
    )
  )
)

server <- function(input, output, session) {
  rval_bmi <- reactive({
    input$weight/(input$height^2)
  })
  output$bmi <- renderText({
    bmi <- rval_bmi()
    # MODIFY CODE BELOW: 
    # Use isolate to stop output from updating when name changes.
    paste("Hi", input$name, ". Your BMI is", round(bmi, 1))
  })
}

shinyApp(ui = ui, server = server)
编辑并运行代码