The app below has two mutually dependent numericInputs, a and b. The value of input$a is 1-input$b and the value of input$b is 1-input$a. Whenever the user changes an input's value, I would like to update the value of the other accordingly. The code below contains two approaches:
- A single observer
- Two separate observers - one that listens for changes to a and updates b and another that listens to
band updatesa.
When I try 1), the inputs get stuck in an infinite loop but I'm not sure I understand why. If the user changes b, then the observer is triggered and the value of a gets updated to be 1-b. Since the values of both inputs are now up-to-date, there are no further changes to input$a or input$b and the observer shouldn't be triggered again until the user makes another change. But this isn't the case.
How exactly does approach 1) differ from approach 2)? Why does 1) get stuck in a loop whereas 2) doesn't?
library(shiny)
shinyApp(
ui = fluidPage(
numericInput('a','a', value = 0.5, max = 1, min = 0),
numericInput('b','b', value = 0.5, max = 1, min = 0)
),
server = function(input, output, session) {
# Using a single observer ----
observe({
updateNumericInput(session, 'a', value = 1-req(input$b))
updateNumericInput(session, 'b', value = 1-req(input$a))
print(input$a)
})
# Using separate observers ----
# observeEvent(input$b, {
# updateNumericInput(session, 'a', value = 1-input$b)
# })
#
# observeEvent(input$a, {
# updateNumericInput(session, 'b', value = 1-input$a)
# })
}
)