0

I want to parallelize making plotOutputs and plots using multiple observers. When I use lapply or mcapply with mc.cores = 1 the plots are re-generated quickly, but when mc.cores is increased, the first set of plots is created upon the first click of the button and subsequent clicks cause huge memory spikes and failure to update. Why?

library(shiny)
library(parallel)
library(ggplot2)

plotsList = list()
plotsReady = reactiveVal(F)
divsReady = reactiveVal(F)

ui = fluidPage(
  fluidRow(actionButton("goPlot", label = "Make 5 plots")),
  fluidRow(uiOutput("plots")
  )
)

server = function(input, output)
{
  # Make and save plots
  observe({
    plots = mclapply(1:5, function(i)
    {
      ggplot(data.frame(x = rnorm(10), y = rnorm(10)), aes(x = x, y = y)) + geom_point()
    }, mc.cores = 5)
    plotsList <<- plots
    plotsReady(T)
  }) %>% bindEvent(input$goPlot)
  
  # Make divs
  observe({
    if(plotsReady())
    {
      output$plots = renderUI({
        lapply(1:length(plotsList), function(i)
        {
          plotOutput(paste0("plot", i), height = 100)
        })
      })
      plotsReady(F)
      divsReady(T)
    }
  })
  
  # Render plots
  observe({
    if(divsReady())
    {
      lapply(1:length(plotsList), function(i)
      {
        output[[(paste0("plot", i))]] = renderPlot(plotsList[[i]])
      })
      divsReady(F)
    }
  })
}

shinyApp(ui, server)
matt
  • 318
  • 3
  • 11

0 Answers0