-
-
Save martinv13/acdc23f037533aaf9a9e9cf4649f5560 to your computer and use it in GitHub Desktop.
An example of interrupting a prolonged, iterative computation in Shiny.
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) | |
appUI <- pageWithSidebar( | |
# Application title | |
headerPanel("New Application"), | |
sidebarPanel( | |
"Progress: ", | |
textOutput("counter"), | |
hr(), | |
"Elapsed Time (seconds):", | |
textOutput("elapsed"), | |
actionButton("stop", "Stop") | |
), | |
mainPanel( | |
textOutput("x") | |
) | |
) | |
appServer <- function(input, output, session) { | |
# The number of iterations to perform | |
maxIter <- 50 | |
# Track the start and elapsed time | |
startTime <- Sys.time() | |
output$elapsed <- renderText({ | |
vals$x | |
round(Sys.time() - startTime) | |
}) | |
# Create a reactiveValues object where we can track some extra elements | |
# reactively. | |
vals <- reactiveValues(x = 0, counter = 0, stop = FALSE) | |
# Update the percentage complete | |
output$counter <- renderText({ | |
paste0(round(vals$counter/maxIter * 100, 1), "%") | |
}) | |
# Show the value of x | |
output$x <- renderText({ | |
round(vals$x,2) | |
}) | |
# Set up a progress indicator | |
progress <- Progress$new() | |
progress$set(message = "Counting...", value = 0) | |
# Do the actual computation here. | |
observe({ | |
isolate({ | |
# This is where we do the expensive computing | |
sum <- 0 | |
for (i in 1:100000){ | |
sum <- sum + rnorm(1) | |
} | |
vals$x <- vals$x + sum | |
# Increment the counter | |
vals$counter <- vals$counter + 1 | |
progress$set(value=vals$counter/maxIter) | |
}) | |
# If we're not done yet, then schedule this block to execute again ASAP. | |
# Note that we can be interrupted by other reactive updates to, for | |
# instance, update a text output. | |
if (isolate(vals$counter) < maxIter && !vals$stop){ | |
invalidateLater(0, session) | |
} else { | |
progress$close() | |
} | |
}) | |
observeEvent(input$stop, { | |
vals$stop <- TRUE | |
}) | |
} | |
shinyApp(appUI, appServer) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment