【问题标题】:Reactive monitoring of a file in Shiny在 Shiny 中对文件进行反应式监控
【发布时间】:2023-01-13 00:30:02
【问题描述】:

我有一个应用程序,我需要在其中监视文件的更改。但是我正在努力做到这一点。

考虑以下示例:

library(shiny)

返回文件修改日期的函数:

file_info <- function(){
  if(file.exists("example.txt")){
    return(as.character(as.Date(file.info("example.txt")[1,4])))
  } else {
    return("File not present")
  }
}

闪亮部分:

ui <- shinyUI(fluidPage(
  textOutput("file_status"),
  actionButton("create_file", "Create file"),
  actionButton("delete_file", "Delete file")
))



server <- shinyServer(function(input, output, session) {
  
  file_st <- reactive(file_info()) #what is the correct approach here?
  
  output$file_status <- renderText({
    file_st()
  })
  
  
  observeEvent(input$create_file,{
    file.create("example.txt")
  })
  
  observeEvent(input$delete_file, {
    unlink("example.txt")
  })
  
})

我希望 file_status 文本字段在每次 example.txt 文件更改时更新 - 如果可能,即使这发生在应用程序之外。

我尝试了 reactiveobservereactiveValues 的各种组合,但没有找到合适的组合。

谢谢

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我能够使用 reactivePoll 解决这个问题,它实际上是为此类任务量身定制的

    server <- shinyServer(function(input, output, session) {
      
      file_st <- reactivePoll(500, session,
                              checkFunc = function() {
                                if (file.exists("example.txt"))
                                  file.info("example.txt")$mtime[1]
                                else
                                  ""},
                              valueFunc = function(){
                                if(file.exists("example.txt")){
                                  return(as.character(as.Date(file.info("example.txt")[1,4])))
                                } else {
                                  return("File not present")
                                }
                              }
      )
      
      output$file_status <- renderText({
        file_st()
      })
      
      
      observeEvent(input$create_file,{
        file.create("example.txt")
      })
      
      observeEvent(input$delete_file, {
        unlink("example.txt")
      })
      
    })
    
    ui <- shinyUI(fluidPage(
      textOutput("file_status"),
      actionButton("create_file", "Create file"),
      actionButton("delete_file", "Delete file")
    ))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2012-09-02
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 2013-10-04
      相关资源
      最近更新 更多