'How to avoid wrapping everything in observeEvent() when passing URL parameters in shiny?

I know that using something like this code:

library(shiny)

ui <- fluidPage(
    mainPanel(
        textOutput("Query_String")
    )
)

server <- function(input, output, session) {
    observeEvent(session$clientData$url_search,{
        Query <- session$clientData$url_search
        output$Query_String <- renderText(Query)
        # Long list of operations dependant on the parameters passed in the URL
    })
}

shinyApp(ui = ui, server = server)

Can enable me to read parameters into my shiny app via URL queries. However it seems like I basically have to wrap my whole server content into one big observe() or observeEvent() to create the needed reactive context. Is there any way to avoid this?



Solution 1:[1]

To avoid recalculating everything if just a single item changed, one wants to create multiple separate observes instead of just a big one. Long code should be refactored in functions e.g. process_query keeping the server function small, allowing to read the overall structure. Important intermediate results can be refactored in their own reactive values (here query). output$Query_String doesn't need to be nested in another reactive context.

process_query <- function(url) {
  # many steps to process the url
  return(url)
}

server <- function(input, output, session) {
  query <- reactive(process_query(session$clientData$url_search))
  output$Query_String <- renderText(query())
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 danlooo