r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
405 stars 56 forks source link

Reactive within R6 classes throws .dependents not found error #137

Closed fabiangehring closed 6 years ago

fabiangehring commented 6 years ago

When using a reactive within an R6 class the following error is thrown: "Error in Test$new()$test() : object '.dependents' not found"

Is there a reason for this behaviour?

library(shiny)
library(R6)

Test <- R6Class(
  classname = "Test",
  public = list(
    test = reactive({
      1
    })
  )
)

isolate(Test$new()$test())

I'm expecting a return value of 1 here instead of the error

wch commented 6 years ago

The reason this happens is that the object that reactive() returns is a special kind of function, and so R6 thinks it is a method. When you instantiate the object, it copies the function and changes its environment, and that's what leads to the error you're seeing.

One more detail: the object returned by reactive() also has some extra stuff attached to it as an attribute. This includes an R6 object of class Observable, as you can see:

> str( reactive({1}) )
function ()  
 - attr(*, "observable")=Classes 'Observable', 'R6' reactive({     1 }) 
 - attr(*, "class")= chr [1:2] "reactiveExpr" "reactive"

It's generally not a good idea to assign an object with reference semantics as a field, as explained here.

The solution given here is a good one: assign the field in the initialize() method.