R-Shiny 响应式编程(二)

江枫思渺然 提交于 2019-12-27 02:41:52

Stop reactions with isolate()

有时observer/endpoint访问响应式值或表达式很有用,但不应依赖于此。 例如,如果observer执行耗时的计算或下载大量数据集,则可能希望其仅在单击按钮时才执行。

为此,我们将使用actionButton。我们将定义一个用户界面,该界面可让用户选择要从正态分布中生成的观察值的数量,并具有一个标有“Go!”的actionButton。您可以在这里看到它的实际效果。

actionButton包含一些JavaScript代码,可以将数字发送到服务器的。当Web浏览器首次连接时,它发送的值为0,并且在每次单击时发送的值都是递增的:1、2、3,依此类推。

ui <- pageWithSidebar(
  headerPanel("Click the button"),
  sidebarPanel(
    sliderInput("obs", "Number of observations:",
                min = 0, max = 1000, value = 500),
    actionButton("goButton", "Go!")
  ),
  mainPanel(
    plotOutput("distPlot")
  )
)

在我们的server函数中,有两点需要注意。首先,仅通过访问output$distPlot即可获取对input$goButton的依赖。单击该按钮时,input$goButton的值增加,因此output$distPlot重新执行。

第二个是,对input$obs的访问用isolate()包装。此函数采用R表达式,并告诉Shiny调用方observer或响应式表达式不应依赖于表达式内的任何响应式对象。

server <- function(input, output) {
  output$distPlot <- renderPlot({
    
    # Take a dependency on input$goButton
    input$goButton

    # Use isolate() to avoid dependency on input$obs
    dist <- isolate(rnorm(input$obs))
    hist(dist)
  })
}

结果图如下所示:

Isolated reactive value

下面是通过输入$obs为1000,然后单击“Go!”按钮时的过程的逐步介绍:

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!