Skip to content

Instantly share code, notes, and snippets.

@jcheng5
Last active July 2, 2020 12:53
Show Gist options
  • Select an option

  • Save jcheng5/cc6647a4971b8125c1bb to your computer and use it in GitHub Desktop.

Select an option

Save jcheng5/cc6647a4971b8125c1bb to your computer and use it in GitHub Desktop.
Pauseable Shiny reactives
# 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