ReactiveR6: ReactiveR6

Description Methods Examples

Description

This class allows you to make your R6 class reactive by inheriting from ReactiveR6 By calling private$invalidate() in a method you can invalidate the class in a controlled way, i.e. only when specific methods are called. See example how to use it.

Inspired by https://community.rstudio.com/t/good-way-to-create-a-reactive-aware-r6-class/84890

Methods

Public methods


Method reactive()

Call this method to make object instance reactive

Usage
ReactiveR6$reactive()

Method clone()

The objects of this class are cloneable with this method.

Usage
ReactiveR6$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
## Not run: 
if (interactive()) {
library(shiny)
library(r6methods)

Counter <-  R6::R6Class(
  "Counter",
  inherit = ReactiveR6,
  public = list(
    increment = function() {
      private$counter <- private$counter + 1
      private$invalidate()
    },
    decrement = function() {
      private$counter <- private$counter - 1
      private$invalidate()
    },
    silent_increment = function() {
      private$counter <- private$counter + 1
    },
    get_counter = function() {
      private$counter
    }
  ),
  private = list(
    counter = 0
  )
)

counter <- Counter$new()$reactive()

shinyApp(
  fluidPage(
    actionButton("increment", "Increment"),
    actionButton("decrement", "Decrement"),
    actionButton("silent_increment", "Silent increment"),
    textOutput("value")
  ),
  function(input, output, session) {
    observeEvent(input$increment, {
      counter()$increment()
    })

    observeEvent(input$decrement, {
      counter()$decrement()
    })

    observeEvent(input$silent_increment, {
      counter()$silent_increment()
    })

    output$value <- renderText({
      counter()$get_counter()
    })
  }
)
}

## End(Not run)

jakubsob/r6methods documentation built on Jan. 22, 2022, 7:42 a.m.