我有一个
shiny
应用程序,它使用在 SQLitebase
中创建的 R
。我想知道我是否可以在使用 future_promises
的同时以某种方式获取结果。现在,当我尝试查询数据库时遇到错误。
library(shiny)
library(promises)
library(future)
plan(multisession)
db <- dbConnect(RSQLite::SQLite(), "", extended_types = TRUE)
dbWriteTable(db, "iris", iris)
nameUI <- function(id) {
ns <- NS(id)
tagList(
selectInput(
inputId = ns("rows"),
label = "Number of rows",
choices = c(10, 50, 100, 150),
selected = 10
),
actionButton(inputId = ns("start_job"),
label = "Start Job",
icon = icon("bolt")),
tableOutput(ns("result_table"))
)
}
nameServer <- function(id) {
moduleServer(
id,
function(input, output, session) {
result_table <- reactiveVal(NULL)
observeEvent(input$start_job, {
print("start")
rows <- input$rows %>% as.numeric()
future_promise({
Sys.sleep(5)
dbSendQuery(db, "SELECT * FROM iris") %>% dbFetch() %>% head(rows)
# iris %>% head(rows)
}) %...>%
result_table()
})
output$result_table <- renderTable({
result_table()
})
}
)
}
app <- function(){
ui <- fluidPage(nameUI("app"))
server <- function(input, output, session){
nameServer("app")
}
shinyApp(ui, server)
}
app()
对于 R 中的 SQLite 数据库的并行查询,您需要连接到 Promise 内的数据库。因此,如果您保存数据库:
db <- dbConnect(RSQLite::SQLite(), "db.sqlite", extended_types = TRUE)
然后这有效:
future_promise({
Sys.sleep(5)
db <- dbConnect(RSQLite::SQLite(), "db.sqlite", extended_types = TRUE)
dbSendQuery(db, "SELECT * FROM iris") %>% dbFetch() %>% head(rows)
}) %...>%
result_table()
如果您正在使用 Promise,您可能需要查看 :
将按钮切换为:
bslib::input_task_button(ns("start_job"),
label = "Start Job",
icon = icon("bolt"))
在服务器中:
task <- ExtendedTask$new(function(rows) {
promises::future_promise({
Sys.sleep(1)
db <- dbConnect(RSQLite::SQLite(), "db.sqlite", extended_types = TRUE)
dbSendQuery(db, "SELECT * FROM iris") %>% dbFetch() %>% head(rows)
}, seed = TRUE)
}) |> bslib::bind_task_button("run")
observeEvent(input$start_job, {
rows <- input$rows %>% as.numeric()
task$invoke(rows)
})
output$result_table <- renderTable({
task$result()
})