简体   繁体   中英

R Shiny observeEvent continues to trigger

I'm struggling to get an observeEvent process to run only once after it's triggering event - a button click. This illustrates:

require(shiny)

ui = fluidPage(
  textInput("input_value", '1. input a value. 2. click button. 3. input another value', ''),
  actionButton("execute", 'execute'),
  textOutput('report')
)

server = function(input, output, session) {
  observeEvent(input$execute, {
    output$report = renderText(input$input_value)
  })
}

shinyApp(ui = ui, server = server, options = list(launch.browser = T))

You'll see that after the button has been clicked once, the textOutput becomes responsive to textInput changes rather than button clicks.

I've tried this approach:

server = function(input, output, session) {
  o = observeEvent(input$execute, {
    output$report = renderText(input$input_value)
    o$destroy
  })
}

No effect. I've also tried employing the isolate function with no luck. Grateful for suggestions.

You probably had your isolate() call wrapped around renderText() instead of input$input_value . This should do it for you:

require(shiny)

ui = fluidPage(
  textInput("input_value", '1. input a value. 2. click button. 3. input another value', ''),
  actionButton("execute", 'execute'),
  textOutput('report')
)

server = function(input, output, session) {
  observeEvent(input$execute, {
    output$report = renderText(isolate(input$input_value))
  })
}

shinyApp(ui = ui, server = server, options = list(launch.browser = T))

Alliteratively you can bring the reactive values into an isolated scope of observeEvent() as below:

library(shiny)

ui = fluidPage(
  textInput("input_value", '1. input a value. 2. click button. 3. input another value', ''),
  actionButton("execute", 'execute'),
  textOutput('report')
)

server = function(input, output, session) {
  observeEvent(input$execute, {

    # bringing reactive values into an isolated scope
    inp_val <- input$input_value

    output$report <- renderText(inp_val)
  })
}

shinyApp(ui = ui, server = server, options = list(launch.browser = T))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM