Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment