首页 > 解决方案 > 依赖的observeEvents导致复杂应用程序出现问题

问题描述

我准备了相当简单的闪亮应用程序,它类似于我更复杂的应用程序中的问题。

我的应用程序的三个必要组件是:

我有两个observeEvents都针对两个反应值。问题是,如果我点击actionButton几次太快,这会创建一个在这两个事件之间切换的循环。Shiny 中是否有任何有效的工具可以在这种情况下提供帮助?例如,防止用户在执行任务之前点击按钮。

# import libraries
library(shiny)
library(ggplot2)
library(dplyr)

ui <- shinyUI(fluidPage(

  sidebarLayout(

    sidebarPanel(
      uiOutput("ui_year"),
      uiOutput("ui_plus")
    ), 

    mainPanel(
      plotOutput("plot1")
    )

)))

server <- shinyServer(function(input, output) {

  # Generate random data
  data <- data.frame(
    year = seq(1900, 2000),
    value = runif(n = 101, min = -3, max = 3)
  )

  # Define two reactive values: add and year
  rv <- reactiveValues()
  rv$add <- 0
  rv$year <- 2000

  # render actionButton
  output$ui_plus <- renderUI({
                 actionButton(inputId = "add",
                          label = paste0(""),
                          icon = icon("plus"))
    })

  # render textInput
  output$ui_year <- renderUI({
             textInput(inputId = "year_1", label = NULL, 
                       value = eval(parse( text = rv$year)),
                       width = "100%",
                       placeholder = NULL)
    })

  # Define two observe events, based on A) action button and B) textInput
  observeEvent(input$year_1, {
    rv$year <- input$year_1
    rv$add <- 0
  })

  observeEvent(input$add, {
    rv$add <- rv$add + 1
    rv$year <- as.numeric(rv$year) + 1
  })

  # Render output
  output$plot1 <- renderPlot({

     sumValue <- as.numeric(rv$year)  + as.numeric(rv$add)

  ggplot(data, aes(x = year, y = value)) + geom_line()+ annotate("text", x = -Inf, y = Inf, hjust = -0.2, vjust = 1, label = sumValue )

  })

  })

shinyApp(ui = ui, server = server)

标签: rshiny

解决方案


推荐阅读