Skip to content

Instantly share code, notes, and snippets.

@Teebusch
Forked from bborgesr/shiny-reactive-R6-object.R
Last active August 15, 2022 05:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Teebusch/b5499570d9d73dd236da7406b4959bc2 to your computer and use it in GitHub Desktop.
Save Teebusch/b5499570d9d73dd236da7406b4959bc2 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), extended to multiple reactive values
library(shiny)
reactiveTrigger <- function() {
counter <- reactiveVal(0L)
list(
listen = function() {
counter()
invisible()
},
trigger = function() {
counter( isolate(counter()) + 1L ) %%
.Machine$integer.max # prevent (very unlikely) integer overflow
}
)
}
Foo <- R6::R6Class(
public = list(
initialize = function(reactive = FALSE) {
private$reactive = reactive
private$value1 = 0
private$value2 = 0
# register reactive triggers
private$triggers = list(
"value1" = reactiveTrigger(),
"value2" = reactiveTrigger()
# ...
)
},
set_value1 = function(x) {
if (private$reactive) private$triggers$value1$trigger()
private$value1 = x
},
get_value1 = function() {
if (private$reactive) private$triggers$value1$listen()
return(private$value1)
},
set_value2 = function(x) {
if (private$reactive) private$triggers$value2$trigger()
private$value2 = x
},
get_value2 = function() {
if (private$reactive) private$triggers$value2$listen()
return(private$value2)
}
),
private = list(
reactive = NULL,
value1 = NULL,
value2 = NULL,
triggers = NULL
)
)
ui <- fluidPage(
numericInput("new_value1", "new value 1", 0),
numericInput("new_value2", "new value 2", 0),
textOutput("value1"),
textOutput("value2")
)
server <- function(input, output, session) {
foo_obj <- Foo$new(reactive = TRUE)
observe({ foo_obj$set_value1(input$new_value1) })
observe({ foo_obj$set_value2(input$new_value2) })
output$value1 <- renderText({ foo_obj$get_value1() })
output$value2 <- renderText({ foo_obj$get_value2() })
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment