Skip to content

Instantly share code, notes, and snippets.

@jcheng5
Created February 28, 2018 00:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcheng5/51596948713d748f32d355b4c7114f2f to your computer and use it in GitHub Desktop.
Save jcheng5/51596948713d748f32d355b4c7114f2f to your computer and use it in GitHub Desktop.
Lazy higher order reactives
library(shiny)
library(dplyr)
library(ggplot2)
dedupe <- function(r) {
x <- reactiveVal(isolate(r()))
o <- observe({
x(r())
})
observe({
o$suspend()
x()
}, priority = 9999999)
r <- reactive({
o$resume()
x()
})
# onInvalidated(r, o$suspend)
r
}
ui <- fluidPage(
checkboxInput("show", "Show plot", TRUE),
sliderInput("hp_range", "Horsepower range", min(mtcars$hp), max(mtcars$hp), c(min(mtcars$hp), max(mtcars$hp))),
conditionalPanel("input.show",
plotOutput("plot")
)
)
server <- function(input, output, session) {
selected_cars <- reactive({
print("Filtering")
mtcars %>% filter(hp >= input$hp_range[1] & hp <= input$hp_range[2])
}) %>% dedupe()
output$plot <- renderPlot({
print("Plotting")
ggplot(selected_cars(), aes(x = mpg, y = disp)) + geom_point()
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment