Level Up with Shiny for R
posit::conf(2024)
2024-08-12
Use long running task from before (long run when changing state)
What if we solved this by adding a “submit button”?
What goes wrong?
_exercises/13_app.R
04:00
Add an actionButton("get_state")
to the sidebar.
Update the schools_state
reactive to only fetch data when the button is clicked.
Use the app. How can you break it?
Reactive graph for long running task
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
Me
You
ExtendedTask
- Step 1Define the task at hand. At its core, it’s a function that returns a future_promise()
#| code-copy: false
task_fetch_data <- ExtendedTask$new(function(data_type) {
future_promise({
fetch_from_slow_api(data_type)
})
}) |>
bind_task_button("fetch_data")
future_promise()
to make it potentially non-blocking
input_task_button()
to this task’s state
ExtendedTask
- Step 2Next, decide when the task will be invoked.
ExtendedTask
- Step 3Finally, use the task’s result in a reactive context.
ExtendedTask
ExtendedTask
server <- function(input, output, session) {
task_fetch_data <- ExtendedTask$new(function(data_type) {
future_promise({
fetch_from_slow_api(data_type)
})
}) |>
bind_task_button("fetch_data")
observeEvent(input$fetch_data, {
task_fetch_data$invoke(input$data_type)
})
data <- reactive({
task_fetch_data$result()
})
}
ExtendedTask
library(future)
library(promises)
future::plan(multisession)
server <- function(input, output, session) {
task_fetch_data <- ExtendedTask$new(function(data_type) {
future_promise({
fetch_from_slow_api(data_type)
})
}) |>
bind_task_button("fetch_data")
observeEvent(input$fetch_data, {
task_fetch_data$invoke(input$data_type)
})
data <- reactive({
task_fetch_data$result()
})
}
_exercises/14_app.R
06:00
Replace the actionButton("get_state")
with an input_task_button()
. How much does the task button help?
Update the server logic to use ExtendedTask
that uses future_promise()
. I’ve already loaded the packages you need.
Can you use the app while fetching data from the API?
Stretch: How could you keep the whole app running, including the plots while the data is being fetched? Read 14_solution2_app.R
for an example.