Launching ShinyStan without blocking R session

This is a neat trick I found on Tyler Morgan-Wall’s Twitter and originally attributed to Joe Cheng. You can run ShinyStan (or anything else Shiny) without blocking the session (which was always a pain point for me). My helper function to run ShinyStan without blocking is below:

launch_shinystan_nonblocking <- function(fit) {
  library(future)
  plan(multisession)
  future(
    launch_shinystan(fit) #You can replace this with any other Shiny app
  )
}

Hope that helps somebody!

7 Likes

Cool trick.
What I have been doing is to save the fit object, reload it from another R session in the Terminal and launch shinystan from there.
It has the advantage that does not require further libraries, and can also be made into a function:

launch_shinystan_bkg <- function(fit) {
  tf <- tempfile()
  saveRDS(fit, tf)
  code_read <- deparse(call("<-", "fit", call("readRDS", tf)))
  code_launch <- "shinystan::launch_shinystan(fit)"
  code <- paste(code_read, code_launch, sep = "; ")
  system(paste("Rscript -e '", code, "' &"))
}

On the downside, it duplicates the object in memory which could be problematic for large objects. Although I’m guessing the future package probably duplicates behind the scene as well.

3 Likes

I get asked about this a lot, so I’m glad these workarounds do the job. Thanks for sharing these!

I did not get either of the proposed methods to work on my Windows system.

What did work for me was to save the stan fit object to an .rds file, writing a R script with the line shinystan::launch_shinystan(readRDS("stan_fit.rds")), and then source that file as a Rstudio Local Job. Very convenient for opening several Shinystan instances in the same time.

1 Like