Arkadi w
Arkadi w

Reputation: 89

R shiny reactivity to trigger only if both inputs changed

I have a relatively simple app with two radioGroupButtons

radioGroupButtons('rng1', label = 'Select metric',
                                                     choices = c('A', 'B', 'C' ),
                                                     selected = 'A', justified = TRUE)

radioGroupButtons('rng2', label = 'Select metric',
                                                     choices = c('A', 'B', 'C' ),
                                                     selected = 'A', justified = TRUE)

I was trying to build a reactivity around observe() or observeEvent() where the reactivity is triggered only when both have changed but it doesn't work.

So in an example such as below (tried many others)

    observe({
      req(input$rng1, input$rng2)
      print('both changed')
    })

this triggers when only 1 changes. I need it to print only when both values were changed.

I believe there must be a very basic solution but am unable to find it.

Thank you for the help

Upvotes: 0

Views: 885

Answers (1)

Pork Chop
Pork Chop

Reputation: 29417

You can maybe use reactiveValues as initial values in the radioGroupButtons which are set to A and then compare it

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
    radioGroupButtons('rng1', label = 'Select metric',choices = c('A', 'B', 'C' ),selected = 'A', justified = TRUE),
    radioGroupButtons('rng2', label = 'Select metric',choices = c('A', 'B', 'C' ),selected = 'A', justified = TRUE)
)

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

    v <- reactiveValues(rng1 = "A",rng2 = "A")    

    observeEvent(c(input$rng1,input$rng2),{
        req(input$rng1 != v$rng1,input$rng2 != v$rng2)
        print('both changed')

        v$rng1 <- input$rng1
        v$rng2 <- input$rng2
    },ignoreInit = TRUE)
}

shinyApp(ui, server)

Upvotes: 1

Related Questions