How to make an operation uninterruptible in R shiny

后端 未结 2 1440
挽巷
挽巷 2021-02-06 04:41

In my shiny app I have a output which should update itself continuously. But whenever I execute a long-running calculation, the output is just paused. My question is: how to mak

相关标签:
2条回答
  • 2021-02-06 05:05

    Thanks @Shree for pointing out the solution. After reading the response from Joe Cheng. It seems like the key is to:

    Hide the async operation from Shiny by not having the promise be the last expression.

    The problem is resolved by creating a reactive value and assign the promise to it in observeEvent as the side effect.

    server <- function(input, output, session) {
    
      output$time <- renderText({
        invalidateLater(1000)
        as.character(Sys.time())
      })
    
      process <- reactiveVal()
    
      observeEvent(input$button,{
        output$isbusy <- renderText("busy") # a simple busy indicator
        future({
          Sys.sleep(5)
          runif(1)
        }) %...>%
          process()
        # Hide the async operation from Shiny by not having the promise be the last expression
        NULL # important
      })
    
      output$result <- renderText({
        output$isbusy <- renderText("") # a simple busy indicator
        process()
      })
    }
    
    0 讨论(0)
  • 2021-02-06 05:21

    Your problem is that Sys.sleep() suspends the execution of R expression. You can use things like the delay() function from shinyjs

    library(shiny)
    library(shinyjs)
    
    ui <- fluidPage(
      useShinyjs(), #You have to add this.
      actionButton("button","Expensive calcualtion(takes 5 seconds)"),
      tags$p("Current Time:"),
      textOutput("time"),
      tags$p("Result from clicking button:"),
      textOutput("result")
    )
    
    server <- function(input, output, session) {
      timer <- reactiveTimer(500)
      current_time <- reactive({
      timer()
      as.character(Sys.time())
     })
     output$time <- renderText(current_time())
    
     observeEvent(input$button,{
     delay(5000, output$result <- renderText("result"))
     })
    }
    
    shinyApp(ui, server)
    
    0 讨论(0)
提交回复
热议问题