OganM
OganM

Reputation: 2663

Asynchronous shiny programming - setting up a basic example

As an exercise, I have modified the default Old Faithful Geyser Data app to incorporate asynchronous programming. However it's behaviour doesn't satisfy my expectations based on my understanding of asynchronous programming I suspect there is a fundamental misunderstanding on my part.

Here, the app creates 2 plot outputs that are identical. One takes longer than the other but set up to work asynchronously, the other is fast.

server.R

library(future)
library(promises)
library(shiny)
plan(multisession)

function(input, output) {

    bins = reactive({
        future({
            print("I'm slow")
            Sys.sleep(10)
            faithful[, 2]
        }) %...>% 
        {seq(min(.), max(.), length.out = input$slow_bins + 1)}
    })

    output$slow_dist_plot <- renderPlot({
        bins() %...>%
        {hist(faithful[, 2], breaks = ., col = 'darkgray', border = 'white')}

    })

    output$fast_dist_plot = renderPlot({
        print("I'm fast")
        x    <-faithful[, 2] 
        bins = seq(min(x), max(x), length.out = input$fast_bins + 1)
        hist(x, breaks = bins, col = 'darkgray', border = 'white')
    })

}

ui.R

library(shiny)

fluidPage(
    titlePanel("Old Faithful Geyser Data"),
    sidebarLayout(
        sidebarPanel(
            sliderInput("slow_bins",
                        "Number of slow bins:",
                        min = 1,
                        max = 50,
                        value = 30),
            sliderInput('fast_bins',
                        'fast bins',
                        min = 1,
                        max = 50,
                        value = 30)
        ),
        mainPanel(
            plotOutput("slow_dist_plot"),
            plotOutput("fast_dist_plot")
        )
    )
)

Based on my understanding of asynchronous programming mainly derived from this Rstudio post, if two users are running this code at the same time, after the initial plotting of the two plots, if one of the users change the slow bins the other user should be free to play around with the fast bins and get instant plots as the other users request is processed by a new process.

However when I actually try this with two windows, I see that whenever I make a change in the slow bin, the other windows have to wait for slow bins to complete. What is going wrong here? Are my expectations wrong or did I set this up wrongly?

Upvotes: 3

Views: 616

Answers (1)

OganM
OganM

Reputation: 2663

Expected behaviour in the question is correct. However, on a single core machine, the number of workers is set to 1 by default when using multisession plan. Doing

plan(multisession,workers = 2)

will have the expected behaviour. Raising the number is probably necessary for an app in live use.

Upvotes: 1

Related Questions