Steve Powell
Steve Powell

Reputation: 1708

How to use debounce with reactiveValues in shiny

I understand that I can use debounce with reactive() like this, and this is the sort of behaviour I need, but I want to use reactiveValues() instead.

ui <- fluidPage(
      textInput(inputId = "text",
                label = "To see how quickly..."),
      textOutput(outputId = "text")
)

server <- function(input, output, session) {
      text_input <- reactive({
            input$text
      })

      debounce(text_input, 2000)

      output$text <- renderText({
            text_input()
      })
}
shinyApp(ui, server)
}

But I would prefer to use reactiveValues() rather than reactive(). Is there any way to use debounce with reactiveValues()? This does not work:

ui <- fluidPage(
  textInput(inputId = "text",
            label = "To see how quickly..."),
  textOutput(outputId = "text")
)

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

  values <- reactiveValues()


  observe({
    values$text= function(x)input$text

  values$t <-
    debounce(values$text(),2000)

  })


  output$text <- renderText({
    values$t()
  })
}
shinyApp(ui, server)

I get an error Warning: Error in r: could not find function "r", I guess because values is not a reactive expression?

Upvotes: 4

Views: 1628

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33550

observe isn't needed:

library(shiny)

ui <- fluidPage(
  textInput(inputId = "text", label = "To see how quickly..."),
  textOutput(outputId = "text")
)

server <- function(input, output, session) {
  values <- reactiveValues()
  values$t <- debounce(reactive({input$text}), 2000)
  output$text <- renderText({
    values$t()
  })
}

shinyApp(ui, server)

Or without reactiveValues:

library(shiny)

ui <- fluidPage(
  textInput(inputId = "text", label = "To see how quickly..."),
  textOutput(outputId = "text")
)

server <- function(input, output, session) {
  debouncedText <- debounce(reactive({input$text}), 2000)
  output$text <- renderText({
    debouncedText()
  })
}

shinyApp(ui, server)

Upvotes: 4

Related Questions