Setting up data refreshing in Shiny app connected to PostgreSQL

岁酱吖の 提交于 2019-12-06 04:27:56

I would use reactivePoll instead of invalidateLater, because it will only re-fetch the whole data in case there is new data.

There is however no way around putting the code to fetch the data inside shinyServer, since your subsequent calculations depend on the (reactive) data.

Disclaimer: I have no experience with SQL whatsoever, and I couldn't test my code due to the lack of a suitable database, but from my understanding of shiny the following code should work.

library(RPostgreSQL)

drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, host='host', port='12345', dbname='mydb',
                 user='me', password='mypass')

check_for_update <- function() {
  dbGetQuery(con, "SELECT MAX(timestamp) FROM table") # edit this part in case
  # the syntax is wrong. the goal is to create an identifier which changes
  # when the underlying data changes
}
get_data <- function() {
  dbGetQuery(con, "select * from table")
}
close_connection <- function() {
  dbDisconnect(con)
  dbUnloadDriver(drv)
}

shinyServer(
  function(input, output, session) {
    # checks for new data every 10 seconds
    data <- reactivePoll(10000, session,
                         checkFunc = check_for_update,
                         valueFunc = get_data)

    # the outputs will only be refreshed in case the data changed
    output$foo <- renderText({
      nrow(data())
    })
    output$bar <- renderText({
      bar <- data() * 2
    })

    session$onSessionEnded(close_connection)
  }
)

Depending on the structure of your app it could be helpful to wrap the calculations into a separate reactive, which you can reuse in several places.

Some notes on code execution with shinyApps can be found in this tutorial.

If you are running into any issues, please leave a comment and I will try to update my post accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!