Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of doing prolonged, iterative computation in Shiny. Adapted from: https://gist.github.com/trestletech/8608815
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