Skip to content

Instantly share code, notes, and snippets.

@bborgesr
Created August 1, 2017 21:22
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bborgesr/3350051727550cfa798cb4c9677adcd4 to your computer and use it in GitHub Desktop.
Save bborgesr/3350051727550cfa798cb4c9677adcd4 to your computer and use it in GitHub Desktop.
Uses the reactiveTrigger() construct in an R6 object class in order to make it useful in reactive settings, like a Shiny app (MWE included)
library(shiny)
reactiveTrigger <- function() {
counter <- reactiveVal( 0)
list(
depend = function() {
counter()
invisible()
},
trigger = function() {
counter( isolate(counter()) + 1 )
}
)
}
counter <- R6::R6Class(
public = list(
initialize = function(reactive = FALSE) {
private$reactive = reactive
private$value = 0
private$rxTrigger = reactiveTrigger()
},
setIncrement = function() {
if (private$reactive) private$rxTrigger$trigger()
private$value = private$value + 1
},
setDecrement = function() {
if (private$reactive) private$rxTrigger$trigger()
private$value = private$value -1
},
getValue = function() {
if (private$reactive) private$rxTrigger$depend()
return(private$value)
}
),
private = list(
reactive = NULL,
value = NULL,
rxTrigger = NULL
)
)
ui <- fluidPage(
actionButton("minus", "-1"),
actionButton("plus", "+1"),
textOutput("value")
)
server <- function(input, output, session) {
count <- counter$new(reactive = TRUE)
observeEvent(input$minus, { count$setDecrement() })
observeEvent(input$plus, { count$setIncrement() })
output$value <- renderText({ count$getValue() })
}
shinyApp(ui, server)
@Teebusch
Copy link

Teebusch commented Jul 21, 2022

Thank you! This is super helpful! I made a fork with an extension to multiple reactive getter functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment