如何从磁盘加载reactiveValues而不破坏观察者?

huangapple go评论81阅读模式
英文:

How to load reactiveValues from disk without breaking obervers?

问题

为了将Shiny应用程序的状态保存到磁盘上,我正在使用函数reactiveValuesToList()

当我想要从磁盘加载状态时,我使用do.call(reactiveValues, ...),就像在这个以前的问题中所示。

但之后observe不再起作用了...


可重现示例

library(shiny)
reactiveConsole(T)

r <- reactiveValues()
r$a <- 1
r$b <- 2

observe(cat("状态:", r$a, r$b))
#> 状态: 1 2

savepath <- tempfile()

save_app_state <- function() {
  saveRDS(reactiveValuesToList(r), savepath)
}

load_app_state <- function() {
  state <- readRDS(savepath)
  r <- do.call(reactiveValues, state)
}

save_app_state()

r$b <- 0
#> 状态: 1 0

load_app_state()

##### 期望结果 #######
#> 状态: 1 0
## 但什么都没有发生

创建于2023年7月23日,使用reprex v2.0.2

英文:

In order to save the state of a shiny application to the disk I am using the function reactiveValuesToList().

When I want to load the state from the disk I am using do.call(reactiveValues, ...) as illustrated in this previous question.

But after that the observers are not working anymore...


Reproducible example

library(shiny)
reactiveConsole(T)

r &lt;- reactiveValues()
r$a &lt;- 1
r$b &lt;- 2

observe(cat(&quot;State:&quot;, r$a, r$b))
#&gt; State: 1 2

savepath &lt;- tempfile()

save_app_state &lt;- function() {
  saveRDS(reactiveValuesToList(r), savepath)
}

load_app_state &lt;- function() {
  state &lt;- readRDS(savepath)
  r &lt;- do.call(reactiveValues, state)
}

save_app_state()

r$b &lt;- 0
#&gt; State: 1 0

load_app_state()

##### EXPECTED #######
#&gt; State: 1 0
## but nothing happens

<sup>Created on 2023-07-23 with reprex v2.0.2</sup>

答案1

得分: 1

你正在创建一个新的reactiveValues对象。执行以下操作:

load_app_state <- function() {
  state <- readRDS(savepath)
  r$a <- state$a
  r$b <- state$b
}
英文:

You are creating a new reactiveValues object. Do:

load_app_state &lt;- function() {
  state &lt;- readRDS(savepath)
  r$a &lt;- state$a
  r$b &lt;- state$b
}

huangapple
  • 本文由 发表于 2023年7月23日 20:08:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76748156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定