在以下闪亮的应用程序中:
单击该按钮时,它每秒打印一次到控制台。
library(shiny)
library(rlang)
ui <- fluidPage(
textOutput("text"),
actionButton("button","Click to Start")
)
server <- function(input, output, session) {
myVal <- reactiveVal(0)
startCount <- reactiveVal(FALSE)
observeEvent(input$button,{
startCount(TRUE)
})
observe({
req(startCount())
req(myVal() < 5)
invalidateLater(1000)
newVal <-myVal() + 1
# myVal(newVal)
print(myVal())
})
output$text <- renderText(myVal())
}
shinyApp(ui, server)
通过删除注释# myVal(newVal)
,它将在控制台中输出1到5,并在UI中显示5。但是有两个问题:
invalidateLater
停止工作,不再等待一秒钟。我应该怎么做才能使其按预期工作?
答案 0 :(得分:1)
您将需要isolate
来避免递归触发观察者:
library(shiny)
library(rlang)
ui <- fluidPage(
textOutput("text"),
actionButton("button","Click to Start")
)
server <- function(input, output, session) {
myVal <- reactiveVal(0)
startCount <- reactiveVal(FALSE)
observeEvent(input$button,{
startCount(TRUE)
})
observe({
req(startCount())
req(isolate(myVal()) < 5)
invalidateLater(1000)
isolate(myVal(myVal() + 1))
print(myVal())
})
output$text <- renderText(myVal())
}
shinyApp(ui, server)