how to avoid repeat computation using reactValues & observer?

Hello, I have no idea how to modify my codes to avoid repeat computation.
What my understood about reactValues is that it stores values for using downstream. There has a Demo.
What I want is that SelectInput value changes then the result changes. But the app will run observe() from beginning. And the message(cor(x, y)) is a code to debug.
Thanks for your time.

# UI
ui <- fluidPage(
  title = "test",
  
  fluidRow(
        column(4, offset = 2,
           uiOutput('selects')
    ),
    column(1, offset = 0,
           uiOutput("txt")
    )
  )
)

# server
server <- function(input, output, session) {
  rct <- reactiveValues()
  
  observe({
    x <- rnorm(1000)
    y <- rnorm(1000)
    message(cor(x, y))
    rct$l <- list(X = 1,
                  Y = "a",
                  Z = "A")
    if (!is.null(input$slt))
      rct$v <- switch(input$slt,
                      X = rct$l$X,
                      Y = rct$l$Y,
                      Z = rct$l$Z)
    
  })
  
  output$selects <- renderUI({
    selectInput("slt",
                label = "values",
                choices = c("X",
                            "Y",
                            "Z"),
                width = "250px"
    )
  })
  output$txt <- renderUI({
    textOutput("txt_content")
  })
  output$txt_content <- renderText({
    rct$v
  })

}

# Run
shinyApp(ui = ui, server = server)

hmmm.
From your description I think you want to change
observe({ i...
into
observeEvent(input$slt,{...

2 Likes

observeEvent worked well.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

Thank you. What my actual app has many middle reactive values, which causes a multiple flows. Although, I would have a try first.