<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/long-running-tasks-with-shiny-challenges-and-solutions/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://blog.fellstat.com/?p=407"> Fells Stats</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>One of the great additions to the R ecosystem in recent years is RStudio’s Shiny package. With it, you can easily whip up and share a user interface for a new statistical method in just a few hours. Today I want to share some of the methods and challenges that come up when the actual computation of a result takes a non-trivial amount of time (e.g >5 seconds).</p>
<h3>First Attempt</h3>
<p>Shiny operates in a <a rel="nofollow" href="https://shiny.rstudio.com/articles/reactivity-overview.html" target="_blank">reactive programming framework</a>. Fundamentally this means that any time any UI element that affects the result changes, so does the result. This happens automatically, with your analysis code running every time a widget is changed. In a lot of cases, this is exactly what you want and it makes Shiny programs concise and easy to make; however in the case of long running processes, this can lead to frozen UI elements and a frustrating user experience.</p>
<p>The easiest solution is to use an <a rel="nofollow" href="https://shiny.rstudio.com/articles/action-buttons.html" target="_blank">Action Button</a> and only run the analysis code when the action button is clicked. Another important component is to provide your user with feedback as to how long the analysis is going to take. Shiny has nice built in <a rel="nofollow" href="https://shiny.rstudio.com/articles/progress.html" target="_blank">progress indicators</a> that allow you to do this.</p>
<div><span><sup><a rel="nofollow" href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" title="WP-CodeBox HowTo?" target="_blank"><span>?</span></a></sup></span><span><a rel="nofollow" target="_blank">View Code</a> R</span>
<div></div>
</div>
<div>
<table>
<tr>
<td>
<pre>library(shiny)
 
# Define UI for application that draws a histogram
ui &lt;- fluidPage(
 
   # Application title
   titlePanel(&quot;Long Run&quot;),
 
   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
        actionButton('run', 'Run')
      ),
 
      # Show a plot of the generated distribution
      mainPanel(
         tableOutput(&quot;result&quot;)
      )
   )
)
 
server &lt;- function(input, output) {
  N &lt;- 10
 
  result_val &lt;- reactiveVal()
  observeEvent(input$run,{
    result_val(NULL)
    withProgress(message = 'Calculation in progress', {
      for(i in 1:N){
 
        # Long Running Task
        Sys.sleep(1)
 
        # Update progress
        incProgress(1/N)
      }
      result_val(quantile(rnorm(1000)))
    })
  })
   output$result &lt;- renderTable({
     result_val()
   })
}
 
# Run the application 
shinyApp(ui = ui, server = server)</pre>
</td>
</tr>
</table>
</div>
<p> </p>
<p><a rel="nofollow" href="https://i2.wp.com/blog.fellstat.com/wp-content/uploads/2018/07/Screen-Shot-2018-07-30-at-10.50.37-AM.png" target="_blank"><img sizes="(max-width: 927px) 100vw, 927px" src="https://i2.wp.com/blog.fellstat.com/wp-content/uploads/2018/07/Screen-Shot-2018-07-30-at-10.50.37-AM.png?w=450" alt="Screen Shot 2018-07-30 at 10.50.37 AM" class="wp-image-415" data-recalc-dims="1"></a></p>
<p> </p>
<p>The above implementation has some of the things we want out of our interface:</p>
<ul>
<li>The long running analysis is only executed when “Run” is clicked.</li>
<li>Progress is clearly displayed to the user.</li>
</ul>
<p>It does have some serious downsides though:</p>
<ul>
<li><strong>If “Run” is clicked multiple times, the analysis is run back to back.</strong> A frustrated user can easily end up having to abort their session because they clicked to many times.</li>
<li><strong>There is no way to cancel the calculation.</strong> The session’s UI is locked while the computation takes place. Often a user will realize that some of the options they’ve selected are incorrect and will want to restart the computation. With this interface, they will have to wait however long the computation takes before they can fix the issue.</li>
<li><strong>The whole server is blocked while the computation takes place.</strong> If multiple users are working with the app, the UIs of all users are frozen while any one user has an analysis in progress.</li>
</ul>
<h3>A Second Attempt With Shiny Async</h3>
<p>Having the whole server blocked is a big issue if you want to have your app scale beyond a single concurrent user. Fortunately, Shiny’s new support of asynchronous processing can be used to remove this behavior. Instead of assigning a value to the reactive value ‘result_val’, we will instead create a promise to execute the analysis in the future (using the future function) and when it is done assign it to result_val (using %…>%).</p>
<div><span><sup><a rel="nofollow" href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" title="WP-CodeBox HowTo?" target="_blank"><span>?</span></a></sup></span><span><a rel="nofollow" target="_blank">View Code</a> R</span>
<div></div>
</div>
<div>
<table>
<tr>
<td>
<pre>library(shiny)
library(promises)
library(future)
plan(multiprocess)
 
# Define UI for application that draws a histogram
ui &lt;- fluidPage(
 
  # Application title
  titlePanel(&quot;Long Run Async&quot;),
 
  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      actionButton('run', 'Run')
    ),
 
    # Show a plot of the generated distribution
    mainPanel(
      tableOutput(&quot;result&quot;)
    )
  )
)
 
server &lt;- function(input, output) {
  N &lt;- 10
 
  result_val &lt;- reactiveVal()
  observeEvent(input$run,{
    result_val(NULL)
    future({
      print(&quot;Running...&quot;)
      for(i in 1:N){
        Sys.sleep(1)
      }
      quantile(rnorm(1000))
    }) %...>% result_val()
  })
  output$result &lt;- renderTable({
    req(result_val())
  })
}
 
# Run the application 
shinyApp(ui = ui, server = server)</pre>
</td>
</tr>
</table>
</div>
<p> </p>
<p><a rel="nofollow" href="https://i0.wp.com/blog.fellstat.com/wp-content/uploads/2018/07/Screen-Shot-2018-07-30-at-11.20.04-AM.png" target="_blank"><img sizes="(max-width: 957px) 100vw, 957px" src="https://i0.wp.com/blog.fellstat.com/wp-content/uploads/2018/07/Screen-Shot-2018-07-30-at-11.20.04-AM.png?w=450" alt="Screen Shot 2018-07-30 at 11.20.04 AM" class="wp-image-418" data-recalc-dims="1"></a></p>
<p> </p>
<p>When “Run” is clicked, the UI is now blocked only for the individual performing the analysis. Other users will be able to perform analyses of there own concurrently. That said, we still have some undesirable properties:</p>
<ul>
<li><strong>If “Run” is clicked multiple times, the analysis is run back to back.</strong></li>
<li><strong>There is no way to cancel the calculation.</strong></li>
<li><strong>The user cannot monitor progress</strong>. Shiny’s progress bar updates do not support calling them from within future, so we’ve had to remove the progress bar from the UI. This is not a huge problem for tasks that take a few seconds, but for those that take minutes or hours, not knowing how long until the results show up can be very frustrating.</li>
</ul>
<h3>Third Time Is the Charm</h3>
<p>In order to solve the cancel and monitoring problems, we need to be able to communicate between the app and the inside of the promise. This can be accomplished with the use of a file, where progress and interrupt requests are read and written. If the user clicks the cancel button, “interrupt” is written to the file. During the course of the computation the analysis code checks whether interrupt has been signaled and if so, throws an error. If no interrupt has been requested, the analysis code writes its progress to the file. If Status is clicked, Shiny reads the file and notifies the user of its contents.</p>
<p>The last addition to the code is to create a reactive value nclicks that prevents the Run button from triggering multiple analyses.</p>
<p> </p>
<div><span><sup><a rel="nofollow" href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" title="WP-CodeBox HowTo?" target="_blank"><span>?</span></a></sup></span><span><a rel="nofollow" target="_blank">View Code</a> R</span>
<div></div>
</div>
<div>
<table>
<tr>
<td>
<pre>library(shiny)
library(promises)
library(future)
plan(multiprocess)
 
ui &lt;- fluidPage(
  titlePanel(&quot;Long Run Stoppable Async&quot;),
  sidebarLayout(
    sidebarPanel(
      actionButton('run', 'Run'),
      actionButton('cancel', 'Cancel'),
      actionButton('status', 'Check Status')
    ),
    mainPanel(
      tableOutput(&quot;result&quot;)
    )
  )
)
 
server &lt;- function(input, output) {
  N &lt;- 10
 
  # Status File
  status_file &lt;- tempfile()
 
  get_status &lt;- function(){
    scan(status_file, what = &quot;character&quot;,sep=&quot;\n&quot;)
  }
 
  set_status &lt;- function(msg){
    write(msg, status_file)
  }
 
  fire_interrupt &lt;- function(){
    set_status(&quot;interrupt&quot;)
  }
 
  fire_ready &lt;- function(){
    set_status(&quot;Ready&quot;)
  }
 
  fire_running &lt;- function(perc_complete){
    if(missing(perc_complete))
      msg &lt;- &quot;Running...&quot;
    else
      msg &lt;- paste0(&quot;Running... &quot;, perc_complete, &quot;% Complete&quot;)
    set_status(msg)
  }
 
  interrupted &lt;- function(){
    get_status() == &quot;interrupt&quot;
  }
 
  # Delete file at end of session
  onStop(function(){
    print(status_file)
    if(file.exists(status_file))
      unlink(status_file)
  })
 
  # Create Status File
  fire_ready()
 
 
  nclicks &lt;- reactiveVal(0)
  result_val &lt;- reactiveVal()
  observeEvent(input$run,{
 
    # Don't do anything if analysis is already being run
    if(nclicks() != 0){
      showNotification(&quot;Already running analysis&quot;)
      return(NULL)
    }
 
    # Increment clicks and prevent concurrent analyses
    nclicks(nclicks() + 1)
 
    result_val(data.frame(Status=&quot;Running...&quot;))
 
    fire_running()
 
    result &lt;- future({
      print(&quot;Running...&quot;)
      for(i in 1:N){
 
        # Long Running Task
        Sys.sleep(1)
 
        # Check for user interrupts
        if(interrupted()){ 
          print(&quot;Stopping...&quot;)
          stop(&quot;User Interrupt&quot;)
        }
 
        # Notify status file of progress
        fire_running(100*i/N)
      }
 
      #Some results
      quantile(rnorm(1000))
    }) %...>% result_val()
 
    # Catch inturrupt (or any other error) and notify user
    result &lt;- catch(result,
                    function(e){
                      result_val(NULL)
                      print(e$message)
                      showNotification(e$message)
                    })
 
    # After the promise has been evaluated set nclicks to 0 to allow for anlother Run
    result &lt;- finally(result,
                      function(){
                        fire_ready() 
                        nclicks(0)
                      })
 
    # Return something other than the promise so shiny remains responsive
    NULL
  })
 
  output$result &lt;- renderTable({
    req(result_val())
  })
 
  # Register user interrupt
  observeEvent(input$cancel,{
    print(&quot;Cancel&quot;)
    fire_interrupt()
  })
 
  # Let user get analysis progress
  observeEvent(input$status,{
    print(&quot;Status&quot;)
    showNotification(get_status())
  })
}
 
# Run the application 
shinyApp(ui = ui, server = server)</pre>
</td>
</tr>
</table>
</div>
<p> </p>
<p><a rel="nofollow" href="https://i0.wp.com/blog.fellstat.com/wp-content/uploads/2018/07/Screen-Shot-2018-07-30-at-11.42.08-AM.png" target="_blank"><img sizes="(max-width: 960px) 100vw, 960px" src="https://i0.wp.com/blog.fellstat.com/wp-content/uploads/2018/07/Screen-Shot-2018-07-30-at-11.42.08-AM.png?w=450" alt="Screen Shot 2018-07-30 at 11.42.08 AM" class="wp-image-420" data-recalc-dims="1"></a> <a rel="nofollow" href="https://i2.wp.com/blog.fellstat.com/wp-content/uploads/2018/07/Screen-Shot-2018-07-30-at-11.41.55-AM.png" target="_blank"><img sizes="(max-width: 963px) 100vw, 963px" src="https://i2.wp.com/blog.fellstat.com/wp-content/uploads/2018/07/Screen-Shot-2018-07-30-at-11.41.55-AM.png?w=450" alt="Screen Shot 2018-07-30 at 11.41.55 AM" class="wp-image-421" data-recalc-dims="1"></a></p>
<p> </p>
<p>All three of the problems with the original async code have been solved with this implementation. That said, some care should be taken when using async operations like this. It is possible for race conditions to occur, especially if you have multiple “Run” buttons in a single app.</p>
<p> </p>
<h3>Final Thoughts</h3>
<p>It is great that Shiny now supports Asynchronous programming. It allows applications to be scaled much more easily, especially when long running processes are present. Making use of these features does add some complexity. The final implementation has ~ 3 times more lines of code compared to the first (naive) attempt.</p>
<p>It is less than ideal that the user has to click a button to get the status of the computation. I’d much prefer it if we were able to remove this button and just have a progress bar; however this is currently not possible within Shiny proper, though it might be achievable to inject some kludgy javascript magic to get a progress bar.</p>
<p> </p>
<p> </p>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://blog.fellstat.com/?p=407"> Fells Stats</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/7m2_IyUMZEk" height="1"></a></div>