Created
August 1, 2017 21:22
-
-
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)
This file contains 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
Thank you! This is super helpful! I made a fork with an extension to multiple reactive getter functions