-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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