Last active
July 2, 2020 12:53
-
-
Save jcheng5/cc6647a4971b8125c1bb to your computer and use it in GitHub Desktop.
Pauseable Shiny reactives
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
| # See ?reactive for meanings of x, env, quoted, and domain. | |
| # paused indicates the starting state of the pauseable reactive. | |
| pauseableReactive <- function(x, env = parent.frame(), quoted = FALSE, | |
| priority = 0, domain = shiny::getDefaultReactiveDomain(), paused = FALSE) { | |
| shiny::installExprFunction(x, "func", eval.env = env, quoted = quoted) | |
| vals <- shiny::reactiveValues(value = NULL) | |
| obs <- shiny::observe(vals$value <- func(), priority = priority, | |
| domain = domain, suspended = paused) | |
| return(structure( | |
| reactive(vals$value), | |
| pauseObserver = obs | |
| )) | |
| } | |
| pause <- function(pausableReactive, pause = TRUE) { | |
| obs <- attr(pausableReactive, "pauseObserver", exact = TRUE) | |
| if (isTRUE(pause)) | |
| obs$suspend() | |
| else | |
| obs$resume() | |
| } | |
| invokeLater <- function(callback, delayMs, | |
| domain = shiny::getDefaultReactiveDomain()) { | |
| initialized <- FALSE | |
| obs <- shiny::observe({ | |
| if (!initialized) { | |
| initialized <<- TRUE | |
| shiny::invalidateLater(delayMs, domain) | |
| return() | |
| } | |
| obs$destroy() | |
| callback() | |
| }, domain = domain) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment