Massoud Mazar

Sharing The Knowledge

NAVIGATION - SEARCH

Show progress bar when pre-loading data in Shiny app

When finishing my capstone project for Coursera's Data Science Certificate track, I needed to load relatively large amount of data (more than 400 MB when loaded). This load operation was taking a few seconds so to let the user of my Shiny app know they need to wait, I decided to use a progress bar.

It is not very complicated, but took me a little time to figure out the right combination. Here are the main points which are shown in following sample code:

  • Define your variables in the root scope (set them to null)
  • In "server" function, check if the variable is null and call your "load" function
  • Pass "session" to load function to be used by "Progress"

And here is the code (summarized):

library(shiny)
library(data.table)

dt2 <- NULL
dt3 <- NULL
dt4 <- NULL
dt5 <- NULL

readData <- function(session, dt2, dt3, dt4, dt5) {
  progress <- Progress$new(session)
  progress$set(value = 0, message = 'Loading...')
  dt2 <<- readRDS("dt2.rds")
  progress$set(value = 0.25, message = 'Loading...')
  dt3 <<- readRDS("dt3.rds")
  progress$set(value = 0.5, message = 'Loading...')
  dt4 <<- readRDS("dt4.rds")
  progress$set(value = 0.75, message = 'Loading...')
  dt5 <<- readRDS("dt5.rds")
  progress$set(value = 1, message = 'Loading...')
  progress$close()
}

ui <- fluidPage(
  ...
)

server <- function(input, output, session) {
  if(is.null(dt5)){
    readData(session, dt2, dt3, dt4, dt5)
  }
  ...
}

# Run the application 
shinyApp(ui = ui, server = server)

 

Add comment