rstudio / promises

A promise library for R
https://rstudio.github.io/promises
Other
198 stars 19 forks source link

Should document that observers wait for promise if returned #46

Open wch opened 5 years ago

wch commented 5 years ago

Here's an app that demonstrates the issue. If the observer's expression returns a promise, then Shiny blocks until that promise is resolved. If, on the other hand, it returns something else, then that promise will still run, but Shiny won't block waiting for it. This is something that both I and @aronatkins have run into, and it would be helpful if it were better documented in https://rstudio.github.io/promises/articles/shiny.html.

library(shiny)
library(future)
library(promises)

plan("multisession")

server <- function(input, output) {
  messages <- reactiveVal()

  observeEvent(input$go, {
    messages('starting sleep in other session...')
    p <- future({
      Sys.sleep(3)
    })
    p <- then(p, function(value) {
      messages(c(messages(), 'completed sleep'))
    })

    if (input$return_value == "NULL") {
      ret <- NULL
    } else if (input$return_value == "promise") {
      ret <- p
    }

    ret
  })

  output$messages <- renderText(
    paste0(messages(), collapse = "\n")
  )
}

ui <- fluidPage(
  p(
    "Returning NULL causes the message to update two times: one time immediately, and one time after ",
    "the future (and subsequent promise) is resolved. "
  ),
  p(
    "Returning a promise causes the message to update only once: Shiny blocks ",
    "until the future (and subsequent promise) is resolved."
  ),
  radioButtons("return_value", "Return value for observer", c("NULL", "promise")),
  actionButton("go", "Go"),
  tags$pre(tags$code(textOutput("messages")))
)

shinyApp(ui = ui, server = server)
jeffkeller87 commented 4 years ago

In particular, this section of the documentation led me to believe that returning a promise in an observer wouldn't be blocking.

https://rstudio.github.io/promises/articles/shiny.html#observers

For anyone who comes across this issue: There are (unsafe) ways of getting around this, such as returning NULL as the last statement in an observer. But, it would be great to have a safe means of doing this. You can indicate your support for such a request by upvoting this issue comment.