|
41 | 41 | #' is, a function that quickly returns a promise) and allows even that very |
42 | 42 | #' session to immediately unblock and carry on with other user interactions. |
43 | 43 | #' |
| 44 | +#' @examplesIf rlang::is_interactive() && rlang::is_installed("future") |
| 45 | +#' |
| 46 | +#' library(shiny) |
| 47 | +#' library(bslib) |
| 48 | +#' library(future) |
| 49 | +#' plan(multisession) |
| 50 | +#' |
| 51 | +#' ui <- page_fluid( |
| 52 | +#' titlePanel("Extended Task Demo"), |
| 53 | +#' p( |
| 54 | +#' 'Click the button below to perform a "calculation"', |
| 55 | +#' "that takes a while to perform." |
| 56 | +#' ), |
| 57 | +#' input_task_button("recalculate", "Recalculate"), |
| 58 | +#' p(textOutput("result")) |
| 59 | +#' ) |
| 60 | +#' |
| 61 | +#' server <- function(input, output) { |
| 62 | +#' rand_task <- ExtendedTask$new(function() { |
| 63 | +#' future( |
| 64 | +#' { |
| 65 | +#' # Slow operation goes here |
| 66 | +#' Sys.sleep(2) |
| 67 | +#' sample(1:100, 1) |
| 68 | +#' }, |
| 69 | +#' seed = TRUE |
| 70 | +#' ) |
| 71 | +#' }) |
| 72 | +#' |
| 73 | +#' # Make button state reflect task. |
| 74 | +#' # If using R >=4.1, you can do this instead: |
| 75 | +#' # rand_task <- ExtendedTask$new(...) |> bind_task_button("recalculate") |
| 76 | +#' bind_task_button(rand_task, "recalculate") |
| 77 | +#' |
| 78 | +#' observeEvent(input$recalculate, { |
| 79 | +#' # Invoke the extended in an observer |
| 80 | +#' rand_task$invoke() |
| 81 | +#' }) |
| 82 | +#' |
| 83 | +#' output$result <- renderText({ |
| 84 | +#' # React to updated results when the task completes |
| 85 | +#' number <- rand_task$result() |
| 86 | +#' paste0("Your number is ", number, ".") |
| 87 | +#' }) |
| 88 | +#' } |
| 89 | +#' |
| 90 | +#' shinyApp(ui, server) |
| 91 | +#' |
44 | 92 | #' @export |
45 | 93 | ExtendedTask <- R6Class("ExtendedTask", portable = TRUE, cloneable = FALSE, |
46 | 94 | public = list( |
|
0 commit comments