r-如何等待输入小部件更新,直到在Shiny中呈现输出



请参阅以下类似问题的无意义最小工作示例:

library(shiny)
ui = shiny::fluidPage(
shiny::sidebarLayout(
shiny::sidebarPanel(
shiny::radioButtons("type", "Type", choices = c("5", "15", "21")),
shiny::sliderInput("x", "x", min = 1, max = 10, value = 7),
shiny::checkboxInput("auto","Set y to 8 when type is 15, and 9 when type is 21", value = TRUE),
shiny::sliderInput("y", "y", min = 1, max = 10, value = 7)
),
shiny::mainPanel(
shiny::plotOutput("show")
)
)
)
server = function(input, output, session) {
plotData = shiny::reactive({
list(x = input$x, y = input$y, type = input$type)
})
output$show = renderPlot({
shiny::req(plotData())
d = plotData()
print("refresh")
plot(d$x,d$y, pch = as.integer(d$type))
})

observe({
n = input$n
a = input$auto
type = input$type
if (type == "a") return(NULL)
if (a) shiny::updateSliderInput(session, "y", value = switch(type, "15" = 8, "21" = 9))
})
}
shiny::shinyApp(ui = ui, server = server)

问题是,当用户选择类型15或21时,该绘图被渲染两次。这是由于当plotData改变时,updateSliderInputrenderPlot之前执行。(我在reactlog包中看到过这种行为。(但是,我不知道如何解决这个问题。我尝试过很多函数,比如isolatereq,但都没有成功。

为了避免不必要地触发反应或输出,在bring:中使用update*函数时,几乎应该始终使用freezeReactiveValue

library(shiny)
ui = shiny::fluidPage(
shiny::sidebarLayout(
shiny::sidebarPanel(
shiny::radioButtons("type", "Type", choices = c("5", "15", "21")),
shiny::sliderInput("x", "x", min = 1, max = 10, value = 7),
shiny::checkboxInput("auto","Set y to 8 when type is 15, and 9 when type is 21", value = TRUE),
shiny::sliderInput("y", "y", min = 1, max = 10, value = 7)
),
shiny::mainPanel(
shiny::plotOutput("show")
)
)
)
server = function(input, output, session) {
plotData = shiny::reactive({
list(x = input$x, y = input$y, type = input$type)
})

observe({
n = input$n
a = input$auto
type = input$type

if (type == "a") return(NULL)
freezeReactiveValue(input, "y")
if (a) shiny::updateSliderInput(session, "y", value = switch(type, "15" = 8, "21" = 9))
}, priority = 1)

output$show = renderPlot({
shiny::req(plotData())
d = plotData()
print("refresh")
plot(d$x,d$y, pch = as.integer(d$type))
})
}
shiny::shinyApp(ui = ui, server = server)

请参阅掌握闪光中的相关章节。

最新更新