Created
May 16, 2017 21:19
-
-
Save przytu1/9bc781645b9ca334ab9fd4ddf36ca145 to your computer and use it in GitHub Desktop.
Asynchronous Shiny calculations with package Future
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
# Author: Zygmunt Zawadzki | |
# http://www.blog.zstat.pl/2017/04/24/make-asynchronous-call-in-shiny./ | |
library(future) | |
library(shiny) | |
plan(multiprocess) | |
ui <- fluidPage( | |
# Application title | |
titlePanel("Old Faithful Geyser Data"), | |
# Sidebar with a slider input for number of bins | |
sidebarLayout( | |
sidebarPanel( | |
sliderInput("bins", | |
"Number of bins:", | |
min = 1, | |
max = 50, | |
value = 30), | |
actionButton("MakePlot", "MakePlot") | |
), | |
# Show a plot of the generated distribution | |
mainPanel( | |
fluidRow( | |
column(6, plotOutput("distPlot")), | |
column(6, plotOutput("FuturePlot"))) | |
) | |
) | |
) | |
# Define server logic required to draw a histogram | |
server <- function(input, output) { | |
output$distPlot <- renderPlot({ | |
# generate bins based on input$bins from ui.R | |
x <- faithful[, 2] | |
bins <- seq(min(x), max(x), length.out = input$bins + 1) | |
# draw the histogram with the specified number of bins | |
hist(x, breaks = bins, col = 'darkgray', border = 'white') | |
}) | |
future <- reactiveValues(future = NULL) | |
output$FuturePlot <- renderPlot({ | |
input$MakePlot | |
x <- NULL | |
isolate({ | |
if(is.null(future$future)) { | |
future$future <- future({ | |
Sys.sleep(5) | |
cbind(rnorm(1000), rnorm(1000)) | |
}) | |
cat("Work scheduled\n") | |
} else if(!resolved(future$future)) { | |
cat("Waiting\n") | |
} else { | |
x <- value(future$future) | |
future$future <- NULL | |
cat("Done!\n") | |
} | |
}) | |
if(is.null(x)) invalidateLater(1000) # Wait 1s | |
req(x) # Stop there if x is still null | |
plot(x) | |
}) | |
} | |
shinyApp(ui = ui, server = server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment