Contenu connexe
Similaire à Shinyユーザのための非同期プログラミング入門 (20)
Shinyユーザのための非同期プログラミング入門
- 18. plan の選択
• 非同期処理をどのように実行するかを plan() で選択する
• plan(multisession)
• 新しいバックグラウンドプロセスを起動し、そこで実行する
• plan(multicore)
• 現在のプロセスからフォークしたプロセスで実行する
• メモリ状態を共有するため高速だが、Windows では使えない
• plan(multiprosess)
• multicore が利用可能ならば multicore を、そうでなければ
multisession を使う
- 20. 注意点
• フューチャコードブロック future({ 処理 }) の内部
ではメインプロセスで生成されたリソースは使えない
• データベース接続、ネットワークソケットなど
• 参照クラスオブジェクトや環境のようなミュータブル
オブジェクトは使えるが、変更はメインプロセスの
オブジェクトには反映されない
• R6 や data.table など
- 31. Shiny への組み込み
• プロミスを Shiny に組み込むにはいくつか制約がある
• future() の中でリアクティブ式は使えない
• プロミスを組み込めるのは次の3つ
① renderXXX()
② オブザーバ
③ リアクティブ式
- 32. future() の中でリアクティブ式は使えない
r1 <- reactive({ ... })
r2 <- reactive({
future({ r1() }) # Error!
})
r1 <- reactive({ ... })
r2 <- reactive({
val <- r1()
future({ val }) # OK!
})
- 33. ① renderXXX() への組み込み
output$table <- renderTable({
read.csv(url) %>%
filter(date == input$date)
})
output$table <- renderTable({
future({ read.csv(url) }) %...>%
filter(date == input$date)
})
- 36. どこが違う?
output$table <- renderTable({
input_date <- input$date
future({ read.csv(url) %>% filter(date == input_date) })
})
output$table <- renderTable({
future({ read.csv(url) }) %...>%
filter(date == input$date)
})
別プロセスで実行
メインプロセス
で実行
- 40. ② オブザーバへの組み込み
• refesh_data ボタンが押されたときにデータを更新する
data <- reactiveVal(readRDS(“cache.rds”))
observerEvent(input$refresh_data, {
df <- read.csv(url)
saveRDS(df, “cache.rds”)
data(df)
})
- 41. ② オブザーバへの組み込み
data <- reactiveVal(readRDS(“cache.rds”))
observerEvent(input$refresh_data, {
future({
df <- read.csv(url)
saveRDS(df, “cache.rds”)
}) %...>%
data()
})
- 43. ③ リアクティブ式への組み込み
data <- eventReactive({
read.csv(url)
})
filteredData <- reactive({
data() %>% filter(date == input$date)
})
output$table <- renderTable({
filteredData() %>% head(5)
})
- 44. ③ リアクティブ式への組み込み
data <- eventReactive({
future({ read.csv(url) })
})
filteredData <- reactive({
data() %...>% filter(date == input$date)
})
output$table <- renderTable({
filteredData() %...>% head(5)
})