suppressMessages(require("reactr"))

NOT FINISHED YET

The underlying registry mechanism of reactr ensures that references of the invisible instances/objects of class ReactiveObject.S3 or ReactiveShinyObject are stored in a registry object (see vignette Registry for details).

Besides being a prerequisite for the caching mechanism that allows the specification of bi-directional bindings (see vignette Bi-Directional Bindings, this also facilitates the use of a push paradigm with respect to reactivity or the way that object state changes are propagation throughout the system.

Below is a short example that illustrates how the push mechanism works.

Scenario description

We set up a very simple example:

Implementation

Ensure that required packages are loaded

pkgs <- c("dplyr", "sendmailR", "RSQLite", "sqldf")
. <- sapply(pkgs, function(pkg) {
  if (!suppressWarnings(require(pkg, character.only = TRUE))) {
    install.packages(pkg)
    require(pkg, character.only = TRUE)
  }
  invisible(NULL)
})

Create reactive object that others can reference:

setReactive(id = "x_1", value = 1)

Define the actual core functions for

updateDatabase <- function(
  id, 
  value, 
  con = file.path(tempdir(), "testdb.sqlite")
) {
  my_db <- src_sqlite(path = con, create = TRUE)

#   dbRemoveTable(db, id)
  this <- data.frame(time = as.character(Sys.time()), value = value)
  if (!id %in% dbListTables(my_db$con)) {
    copy_to(my_db, this, id, temporary = FALSE) # need to set temporary to FALSE 
  }

  sql <- sprintf(
    'INSERT INTO %s VALUES (%s, %s)', 
    id, paste0("\"", Sys.time(), "\""), value
  )
  dbSendQuery(my_db$con, sql)
#   dbReadTable(my_db$con, id)
  message("Updated database")
  TRUE
}

sendEmail <- function(id, value, con) {

}

Database connection settings

con <- file.path(tempdir(), "testdb.sqlite")
my_db <- src_sqlite(path = con, create = TRUE)
try(dbReadTable(my_db$con, "x_1"), silent = TRUE)

Push in action

setReactive(
  id = "pushToDatabase", 
  value = function() {
    "object-ref: {id: x_1}"
    updateDatabase(
      id = "x_1", 
      value = x_1,
      con = file.path(tempdir(), "testdb.sqlite")
    )
    TRUE
  }, 
  push = TRUE
)

x_1 <- 2
x_1 <- 3
x_1 <- 4
x_1 <- 5

## Inspect database //
dbReadTable(my_db$con, "x_1")

Note that we never explicitly called pushToDatabase.

It was called whenever x_1 changed.

Clean up

rmReactive("x_1")
rmReactive("x_2")


rappster/reactr documentation built on May 26, 2019, 11:56 p.m.