Search code examples
rshinyreactive-programmingreactiveshiny-reactivity

How to load reactiveValues from disk without breaking obervers?


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 <- reactiveValues()
r$a <- 1
r$b <- 2

observe(cat("State:", r$a, r$b))
#> State: 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
#> State: 1 0

load_app_state()

##### EXPECTED #######
#> State: 1 0
## but nothing happens

Created on 2023-07-23 with reprex v2.0.2


Solution

  • You are creating a new reactiveValues object. Do:

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