本文介绍了无法呈现“正在加载"消息.使用Shiny和期货的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用期货来显示正在加载"图标.这是我的代码

I am trying to use futures to have a "loading" icon appear. This is the code I have

library(shiny)
library(promises)
library(future)
plan(multiprocess) 

disksUI <- function(id) {
  ns <- NS(id)
  fluidRow(
    box(
      uiOutput(ns("loading")),
      dataTableOutput(ns("filelist")),
      width=12
    )
  )
}

disksServer <- function(input, output, session) {
  state <- reactiveValues(onLoading=FALSE)

  observe({
    if (state$onLoading) {
      output$loading <- renderUI("Loading")
    } else {
      output$loading <- renderUI("Done")
    }
  })

  filelist <- reactive(
    {
      state$onLoading <- TRUE
      future({
        Sys.sleep(3)
        state$onLoading <- FALSE
       }
      )
    }
  )

  output$filelist <- renderDataTable({
    filelist()
  })

}

但是,结果不是我所期望的.我期望的是

However, the result is not what I expect. What I expect is

  • 正在加载"字符串立即出现
  • 三秒钟后,字符串Loading被替换为Done

会发生什么

  • 三秒钟什么都没写.
  • 三秒钟后,出现正在加载的字符串.

推荐答案

我发布了我的答案此处.但是,请在此处为以后的读者添加它:

I posted my answer here first. However, adding it also here for future readers:

这是一个有效的示例:

library(shiny)
library(shinydashboard)
library(promises)
library(future)
library(shinyjs)
plan(multiprocess)

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

  output$loading <- renderUI("Idling")

  myFilelist <- reactiveVal(NULL)

  observeEvent(input$getBtn, {

    disable("getBtn")
    output$loading <- renderUI("Loading")

    myFuture <- future({
      Sys.sleep(3)
      data.frame(list.files(getwd()))
    })

    then(myFuture, onFulfilled = function(value) {
      enable("getBtn")
      output$loading <- renderUI("Done")
      myFilelist(value)
    },
    onRejected = NULL)

    return(NULL)
  })

  output$filelist <- renderDataTable({
    myFilelist()
  })

}

ui <- fluidPage(
  useShinyjs(),
  fluidRow(
    actionButton("getBtn", "Get file list"),
    box(
      uiOutput("loading"),
      dataTableOutput("filelist"),
      width=12
    )
  )
)

shinyApp(ui, server)

请注意observeEvent()中的return(NULL)-这在其自己的会话中隐藏了未来-允许会话内响应.但是,现在,我们必须处理潜在的比赛条件,就像郑成(Joe Cheng)向您提到的这里.在这个简单的示例中,我们可以禁用触发按钮,以避免用户在其他人仍在处理中的同时创建新期货的可能性.有关更多详细信息,请阅读.

Please note the return(NULL) in the observeEvent() - this is hiding the future from its own session - allowing intra-session responsiveness. However, now we have to deal with potential race conditions, as Joe Cheng already mentioned to you here. In this simple example we can disable the trigger button to avoid users having the possibility of creating new futures while others are still beeing processed. For further details please read this.

这篇关于无法呈现“正在加载"消息.使用Shiny和期货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:50