Created
March 6, 2017 16:53
-
-
Save bborgesr/115b5e36eb2fbb511136d6e596876a6e to your computer and use it in GitHub Desktop.
An example of doing prolonged, iterative computation in Shiny. Adapted from: https://gist.github.com/trestletech/8608815
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
library(shiny) | |
ui <- fluidPage( | |
sidebarLayout( | |
sidebarPanel( | |
numericInput("steps", "Time steps:", 10, min=1), | |
actionButton("run", label="Start") | |
), | |
mainPanel( | |
textOutput("status") | |
) | |
) | |
) | |
server <- function(input, output, session) { | |
vals <- reactiveValues(running = FALSE, step = 0, run = 1, label = "Start") | |
# helper functions | |
toggleLabel <- function() { | |
if (vals$label %in% c("Start", "Resume")) vals$label <- "Stop" | |
else vals$label <- "Resume" | |
vals$label | |
} | |
observe({ | |
req(input$run) | |
isolate({ | |
# update label when the button is clicked and stop/resume computation | |
if (input$run != vals$run) { | |
updateActionButton(session, "run", label = toggleLabel()) | |
vals$run <- input$run | |
vals$running <- !vals$running | |
} | |
# update label and vals$running the first time around only | |
if (vals$label == "Start") { | |
updateActionButton(session, "run", label = toggleLabel()) | |
vals$running <- TRUE | |
} | |
}) | |
# 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$step < input$steps) && vals$running })) { | |
Sys.sleep(1) # placeholder for computation | |
vals$step <- isolate(vals$step) + 1 | |
invalidateLater(0, session) | |
} | |
}) | |
output$status <- renderText({ | |
paste("You're on iteration number:", vals$step) | |
}) | |
} | |
shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment