1

The app below contains an actionButton that triggers an lapply when clicked. The lapply loops through the numbers 2-4 and stops if x %% 2 is not 0. Is it possible to break the lapply without stopping the main app?

library(shiny)

ui <- fluidPage(
  actionButton(inputId = "go", label = "Start"),
  div(id = 'placeholder')
)

server <- function(input, output, session) {

  observeEvent(input$go, {

    lapply(2:4, function(x) {

      res = x %% 2

      if(res == 0){

        return(x)

      } else {

        insertUI('#placeholder', ui = tags$p('There was an error.'))

        stop('Error')
      }
    })
  })

}

shinyApp(ui = ui, server = server)

req is not an option since I need to insert some UI just before terminating the loop if the x %% 2 == 0 condition isn't met.

I have found a similar question here: Is it possible to stop executing of R code inside shiny (without stopping the shiny process)?. But it relies on the user input to stop execution and I'm not sure how to modify it to this example. I also can't attempt to modify it because parallel is not available for R version 3.6.0. I also saw this post referenced here: https://github.com/rstudio/shiny/issues/1398 but I think it requires user input as well.

user51462
  • 1,658
  • 2
  • 13
  • 41

1 Answers1

0

Depending on the exact requirements in your app, maybe you can use a "normal" loop and use break to stop the loop execution. Alternatively, you could wrap it in a try call:

server <- function(input, output, session) {

  observeEvent(input$go, {

    try(lapply(2:4, function(x) {

      res = x %% 2

      if(res == 0){

        return(x)

      } else {

        insertUI('#placeholder', ui = tags$p('There was an error.'))

        stop('Error')
      }
    }), silent=T)
  })

}
bobbel
  • 1,983
  • 6
  • 21