以下是基于您的代码片段的会话内非阻塞期货示例:
library(shiny)
library(promises)
library(future)
plan(multiprocess)
twoMinFunction <- function(){
return(Sys.time())
}
sixHourFunction <- function(){
Sys.sleep(3)
return(Sys.time())
}
server <- function(input, output, session) {
values <- reactiveValues(twominresult = NULL, sixhourresult = NULL)
observe({
# Re-execute this reactive expression every 2 seconds # mins
invalidateLater(2000, session) # 120000
myTwoMinFuture <- future({
twoMinFunction()
})
then(myTwoMinFuture, onFulfilled = function(value) {
values$twominresult <- value
},
onRejected = NULL)
return(NULL)
})
observe({
# Re-execute this reactive expression every 6 seconds # hours
invalidateLater(6000, session) # 21600000
mySixHourFuture <- future({
sixHourFunction()
})
then(mySixHourFuture, onFulfilled = function(value) {
values$sixhourresult <- value
},
onRejected = NULL)
return(NULL)
})
output$twominout <- renderText({
paste("two min result:", values$twominresult)
})
output$sixhoursout <- renderText({
paste("six hour result:", values$sixhourresult)
})
}
ui <- fluidPage(textOutput("twominout"),
textOutput("sixhoursout"))
shinyApp(ui, server)
我让它快了一点,所以你可以看到变化。
请注意- 这隐藏return(NULL)了observeEvent()它自己的会话的未来 - 允许会话内响应。请记住,如果使用错误的方式,这种模式可能会导致竞争条件(请参阅 Joe Cheng 的评论,我已经在上面提到过)