Shiny: How to stop processing invalidateLater() after data was abtained or at the given time

后端 未结 2 494
日久生厌
日久生厌 2020-12-11 12:14

I want to keep reflashing until 10:05, after 10:05 I got the tplus0_dt and stop to processing invalidaterLater().

Before 10:00, tplus0_dt doesn\'t exist, so I need

2条回答
  •  春和景丽
    2020-12-11 12:53

    Although you'd never realize it from the Shiny documentation, invalidateLater() actually only returns to your reactive once. The reason it seems to return repeatedly is that on each trip the invalidateLater() function gets run again.

    So the solution is to use a conditional around the function so that you don't keep repeatedly calling it:

    if(runMeAgain) {
       invalidateLater(n)
    }
    
    runMeAgain = TRUE   # your reactive re-runs every n milliseconds
    runMeAgain = FALSE  # your reactive does not re-run
    

    Also note that:

    • invalidateLater() is non-blocking (other code can run while you wait)
    • invalidateLater() doesn't stop the rest of the reactive from running. If you want to stop the reactive at that point in the code, put a return() after invalidateLater()
    • invalidateLater() gets isolated() inside an observeEvent() or eventReactive() and consequently doesn't work; you have to use observe() or reactive(). It might also work inside a render function, but I haven't ever had a reason to try that.

    In terms of the original question, the reactive should look like this:

    get_tplus0_data <- reactive({
        time <- substr(as.character(Sys.time()), 12, 16)
        if(time >= "10:05"){
            tplus0_dt<- data.table(a = c(1, 2, 3, 4), b = c(3, 4, 5, 8)) 
            return(tplus0_dt)
        } else {
            invalidateLater(1000)
            return()
        }
    })
    

提交回复
热议问题