Chapter 15. Reactive Building Blocks

Now that you have the theory underpinning the reactive graph and you’ve got some practical experience, this is a good time to talk in more detail about how reactivity fits into R, the programming language. There are three fundamental building blocks of reactive programming: reactive values, reactive expressions, and observers. You’ve already seen most of the important parts of reactive values and expressions, so this chapter will spend more time on observers and outputs (which as you’ll learn are a special type of observer). You’ll also learn two other tools for controlling the reactive graph: isolation and timed invalidation.

This chapter will again use the reactive console so that we can experiment with reactivity directly in the console without having to launch a Shiny app each time. To begin, we’ll load shiny and turn on reactivity for interactive experimentation:

library(shiny)
reactiveConsole(TRUE)

Reactive Values

There are two types of reactive values:

  • A single reactive value, created by reactiveVal()

  • A list of reactive values, created by reactiveValues()

They have slightly different interfaces for getting and setting values:

x <- reactiveVal(10)
x()       # get
#> [1] 10
x(20)     # set
x()       # get
#> [1] 20

r <- reactiveValues(x = 10)
r$x       # get
#> [1] 10
r$x <- 20 # set
r$x       # get
#> [1] 20

It’s unfortunate that these two similar objects have rather different interfaces, but there’s no way to standardize them. However, while they look different, ...

Get Mastering Shiny now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.