Iām trying to develop an Rshinyapp that requires clicking a button to perform tasks such as data processing and plotting. Upon clicking the button, the UI will display another button to analyze data and save images.
Due to this logical relationship, I have implemented nested observeEvent to achieve the desired functionality. However, the issue now is that every time the second button is clicked, the inner observeEvent not only runs once, but also runs a number of times equal to the cumulative number of times the first button has been clicked. This redundancy in computation is negatively impacting the efficiency of the software. How can I solve this problem?
In the following simple example, I have simplified and reproduced the problem I encountered. You can try running this code and clicking the first and second buttons multiple times to observe the issue I mentioned.
library(shiny)
ui <- fluidPage(
actionButton("b1", "button 1"),
actionButton("b2", "button 2"),
)
server <- function(input, output, session) {
x <- 1
cat(sprintf("out x = %d \n", x))
cat("sleep: 1s \n")
Sys.sleep(1)
observeEvent(input$b1,{
# Every time you click button 1, the code below will run once.
x <<- x+1
cat(sprintf("ob1 x = %d \n", x))
cat("sleep: 1s \n")
Sys.sleep(1)
observeEvent(input$b2, {
# Clicking button 2 once will trigger the code below to run multiple times,
# equal to the cumulative number of times you have clicked button 1.
x <<- x+1
cat(sprintf("ob2 x = %d \n", x))
cat("sleep: 1s \n")
Sys.sleep(1)})
})
}
shinyApp(ui, server)
I think this nested structure is irreplaceable because the second button only displays when the correct data is inputted, and for ease of operation, the inputted data is saved in an observeEvent for use or modification. I have tried to replace observeEvent with eventReactive, or add the ignoreInit = TRUE parameter, but these attempts did not work.
There are some similar issues, but it seems they don't solve my problem. You can use them as a reference: ref.1, ref.2
Thanks in advance to anyone who tries to help me.