Skip to content

Instantly share code, notes, and snippets.

@jimbrig
Forked from bborgesr/shiny-reactive-R6-object.R
Created December 4, 2024 22:02
Show Gist options
  • Save jimbrig/3c443c4c7b0c46cbc515ed26fd91ced2 to your computer and use it in GitHub Desktop.
Save jimbrig/3c443c4c7b0c46cbc515ed26fd91ced2 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment