-
Notifications
You must be signed in to change notification settings - Fork 41
/
15-reactive-building-blocks.Rmd
661 lines (462 loc) · 13.8 KB
/
15-reactive-building-blocks.Rmd
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
# Reactive Building Blocks
**Learning Objectives**
- Building blocks:
- Reactive values
- Reactive expressions
- Observers
- How these tools are built from low-level functions:
- `observe()`
- `isolate()`
- How error messages / signal conditions move on reactive graph
- Shiny reactive values are built on reference-semantics
## Types of Reactive Values {-}
| |**reactiveVal()**|**reactiveValues()**|
|:----|:----------------|:-------------------|
|Holds|A **single** reactive value|A **list** of reactive values|
|Definition|`x <- reactiveVal(1)`|`x <- reactiveValues(a = 1, b = 2)`|
|Getting syntax|`x()`|`x$a`|
|Setting syntax|`x(2)`|`x$a <- 2`|
|Class|reactiveVal reactive function|reactivevalues|
## Copy-on-modify Semantics {-}
If you create an object with some value.
```{r}
x1 <- 10
```
And you copy the same value on a new object.
```{r}
x2 <- x1
```
## Copy-on-modify Semantics {-}
Then if you modify the original object.
```{r}
x2 <- 20
```
That won't change the value of the original object.
```{r}
x1
```
## Copy-on-modify Semantics {-}
If we create a list.
```{r}
x <- list(a = 1, b = 1)
```
And a function to modify the element "a" of the list.
```{r}
f <- function(x) {
x$a = 2
invisible(x)
}
```
## Copy-on-modify Semantics {-}
After applying the function to the original list will return a new object.
```{r}
f(x) |> unlist()
```
Rather than modifying the original list.
```{r}
x |> unlist()
```
## Reference Semantics (shiny) {-}
If you are working in the server function of the app.
```{r}
library(shiny)
reactiveConsole(TRUE)
```
You can copy the value of a reactive value to new object.
```{r}
b1 <- reactiveValues(x = 10)
b2 <- b1
```
But if you change the original reactive variable.
```{r}
b1$x <- 20
```
Then the copy also changes.
```{r}
b2$x
```
## Reference Semantics (R6) {-}
If you create a new object R6 object.
```{r}
y1 <- R6::R6Class("Y", list(a = 1, b = 1))$new()
```
An you copy that object.
```{r}
y2 <- y1
```
## Reference Semantics (R6) {-}
Then if you modify the value of the new object.
```{r}
y2$b <- 2
```
Then the original object also changes.
```{r}
y1 |> unlist()
```
## Reference Semantics (R6) {-}
If a function changes the value of the original object.
```{r}
f(y1)
```
Then the copy also get changed.
```{r}
y2
```
## Exercises {-}
1. *What are the differences between these two lists of reactive values? Compare the syntax for getting and setting individual reactive values.*
```{r}
# Defining values
l1 <- reactiveValues(a = 1, b = 2)
l2 <- list(a = reactiveVal(1), b = reactiveVal(2))
# ... with a little extra
l3 <- reactiveVal(list(a = 1, b = 2))
```
```r
# Getting
l1$a; l1[["a"]]
l2$a(); l2[["a"]]()
l3()$a; l3()[["a"]]
# Setting
l1$a <- 15
l2$a(15)
# For l3, can't easily update just 'a'
l3(list(a = 15, b = 2))
```
## Exercises {-}
2. *Design and perform a small experiment to verify that reactiveVal() also has reference semantics.*
```{r}
# If we define 3 objects
x <- reactiveVal(1)
y <- x
z <- reactiveVal(1)
# If we change the value of x
x(2)
# Then y also changes
x()
y()
# But z keeps the same
z()
```
## Reactive Expressions: Cached Errors {-}
Errors are **cached** just as values.
```{r, eval=FALSE}
r <- reactive(stop("Error occured at ", Sys.time(), call. = FALSE))
r()
```
```{r, echo=FALSE}
r <- reactive(stop("Error occured at ", Sys.time(), call. = FALSE))
try(r())
```
So if you run it again, it **won't update** the message.
```{r, eval=FALSE}
Sys.sleep(2)
r()
```
```{r, echo=FALSE}
Sys.sleep(2)
try(r())
```
## Reactive Expressions: Propagated Errors{-}
Errors are **propagated** through the reactive graph just as values, but they present different behavior when they reach an:
- **Output**: The error will be displayed in the app.
- **Observer**: The error will cause the current session to terminate.
- This can be avoided by wrapping the code in `try()` or `tryCatch()` functions.
*From: examples/15-reactive-blocks/01-error-propagated-example.R*
```{r}
#| echo: true
#| eval: false
#| file: examples/15-reactive-blocks/01-error-propagated-example.R
```
## Reactive Expressions: Errors `seq()` {-}
If some error is present in next function:
- Observers and outputs to **stop what they’re doing** but not otherwise fail.
- By default, it will cause outputs to reset to their **initial blank state**, unless `req(..., cancelOutput = TRUE)` they’ll preserve their current display.
*From: examples/15-reactive-blocks/02-seq-error-example.R*
```{r}
#| echo: true
#| eval: false
#| file: examples/15-reactive-blocks/02-seq-error-example.R
```
## Where does `on.exit()` work? {-}
`on.exit()` can be used on:
- Inside [function bodies](https://adv-r.hadley.nz/functions.html#on-exit)
- In [testthat expressions](https://www.tidyverse.org/blog/2020/04/self-cleaning-test-fixtures/)
- In a **reactive expression or observer**
When does `on.exit()` run?
- In functions, the code in `on.exit()` runs after all the rest of the code has run.
- It runs even if there are errors / warnings.
- You can have multiple calls to `on.exit()` inside a function (use add = TRUE, so a call doesn't overwrite an earlier one)
## Applications of `on.exit()` {-}
- Set an R option
- Set an environment variable
- Change working directory
- Create a file or directory
- Create a resource on an external system
```{r}
neat <- function(x, sig_digits) {
op <- options(digits = sig_digits)
on.exit(options(op), add = TRUE)
print(x)
}
neat(pi, 2)
pi
```
## Observers and Outputs {-}
Observers and outputs are terminal nodes in the reactive graph.
- Reactives : cached and lazy
- Observers / Outputs : forgetful and eager *(if they were lazy, nothing would get done)*
![](images/15-reactive-blocks/01-output-observer-reactive-graph.png)
## Observers and Outputs {-}
`observeEvent()` is used for:
- Saving a file to a shared network drive
- Sending data to a web API
- Updating a database
- Printing a debugging message to the console
> The **value returned by an observer is ignored** because they are designed to work with functions called for their side-effects
In the other side, **Outputs**:
- Running `output$text <- ...` creates the observer.
- They can detect when they're not **visible** so they don't have to **recompute**
## `observe()` Function {-}
Observers and Outputs use `observe()`.
`observe()` sets up a block of code that is run **every time one** of the reactive values or expressions it uses is updated.
```r
y <- reactiveVal(10)
observe({
message("`y` is ", y())
})
#> `y` is 10
y(5)
#> `y` is 5
y(4)
#> `y` is 4
```
## `observe()` Propertites {-}
Every time you run the `observe()` function it **creates** an action that can be triggered.
In the next example, every time x changes, it creates another observer, so its value is printed another time.
```r
x <- reactiveVal(1)
y <- observe({
x()
observe(print(x()))
})
#> [1] 1
x(2)
#> [1] 2
#> [1] 2
x(3)
#> [1] 3
#> [1] 3
#> [1] 3
```
> You should only ever create **observers or outputs at the top-level** of your server function.
## Isolating Code {-}
To avoid creating reactive dependencies when not needed, we can use the functions:
- `isolate()`
- `observeEvent()`
- `eventReactive()`
## Using the `isolate` Function {-}
For example, the next code creates an **infinite loop** because the observer will take a reactive dependency on `x` **and** `count`.
```r
r <- reactiveValues(count = 0, x = 1)
observe({
r$x
r$count <- r$count + 1
})
```
As we don't want to create dependency based on `r$count` we can isolate it.
```r
r <- reactiveValues(count = 0, x = 1)
observe({
r$x
r$count <- isolate(r$count) + 1
})
r$x <- 1
r$x <- 2
r$count
#> [1] 2
r$x <- 3
r$count
#> [1] 3
```
## Using the `observeEvent` Function {-}
But if we need to isolate many variables in a script is better to use `observeEvent(x, y)` which is equivalent to `observe({x; isolate(y)})` to get the same results.
```r
observeEvent(r$x, {
r$count <- r$count + 1
})
r$x <- 8
r$count
#> [1] 4
```
`eventReactive(x, y)` on the other hand is equivalent to use `reactive({x; isolate(y)})`
## `observeEvent` and `eventReactive` arguments {-}
- `ignoreNULL = FALSE` to also handle NULL values, rather than ignoring any event that yields NULL.
- `ignoreInit = TRUE` to avoid running the functions the functions once when you create them.
- `once = TRUE` to run the handler only once.
*From: examples/15-reactive-blocks/03-isolate-example.R*
```{r}
#| echo: true
#| eval: false
#| file: examples/15-reactive-blocks/03-isolate-example.R
```
## Review to `reactiveTimer()` {-}
![](images/15-reactive-blocks/02-timing-timer.png)
```r
server <- function(input, output, session) {
timer <- reactiveTimer(500)
x1 <- reactive({
timer()
rpois(input$n, input$lambda1)
})
x2 <- reactive({
timer()
rpois(input$n, input$lambda2)
})
output$hist <- renderPlot({
freqpoly(x1(), x2(), binwidth = 1, xlim = c(0, 40))
}, res = 96)
}
```
## Understanding `invalidateLater(ms)` {-}
After `ms` milliseconds it causes any **reactive consumer to be invalidated**.
That is useful for:
- Creating animations
- Connecting to data sources outside of Shiny’s reactive framework
## Understanding `invalidateLater(ms)` {-}
Generate 10 fresh random normals every half a second
```r
x <- reactive({
invalidateLater(500)
rnorm(10)
})
```
## Understanding `invalidateLater(ms)` {-}
Increment a cumulative sum with a random number
```r
sum <- reactiveVal(0)
observe({
invalidateLater(300)
sum(isolate(sum()) + runif(1))
})
```
## Importing data {-}
To import data only when the data have been updated you can use the `reactivePoll()` function.
```r
server <- function(input, output, session) {
data <- reactivePoll(1000, session,
function() file.mtime("data.csv"),
function() read.csv("data.csv")
)
}
```
But for this simple example we can also use `reactiveFileReader()` function.
```r
server <- function(input, output, session) {
data <- reactiveFileReader(1000, session, "data.csv", read.csv)
}
```
## Long running reactives {-}
In the next code we are invalidating the result before ending a log process which ends in an **infinitive invalidation loop**.
```r
x <- reactive({
# Invalidation
invalidateLater(500)
# Long Process
Sys.sleep(1)
# Output
10
})
```
But if we wrap the invalidation function into an `on.exit` function, we will make sure to run check after ending the process.
```r
x <- reactive({
# Invalidation
on.exit(invalidateLater(500), add = TRUE)
# Long Process
Sys.sleep(1)
# Output
10
})
```
## Timer accuracy {-}
The number of milliseconds specified in `invalidateLater()` is a **polite request**, not a demand.
This effectively means that the **invalidation might take longer** than you expect.
## Meeting Videos
### Cohort 1
`r knitr::include_url("https://www.youtube.com/embed/uwawZNrU-5k")`
<details>
<summary> Meeting chat log </summary>
```
01:04:02 Andrew MacDonald: I’m afraid i ahve to duck out early today. Please let me know if we still need somebody for next week!
01:04:09 Andrew MacDonald: thanks so much Russ et al! :D
01:04:18 [email protected]: thanks
01:04:40 [email protected]: are there any example apps ?
01:11:12 Layla Bouzoubaa: Thanks russ! Need to hop off!
01:14:19 Anne Hoffrichter: Thanks Russ! See you next week!
01:14:34 russ: Bye
```
</details>
### Cohort 2
`r knitr::include_url("https://www.youtube.com/embed/q2d3uBHO3Tk")`
<details>
<summary> Meeting chat log </summary>
```
00:37:01 Ryan Metcalf: Really good topic on Linked List in C++. The discussion was related to memory management. https://www.geeksforgeeks.org/data-structures/linked-list/
00:45:12 Kevin Gilds: Reactive Values in Modules
00:45:39 Kevin Gilds: The inputs across across modules
00:47:27 Kevin Gilds: I will put some articles in the slack reactive values and modules
```
</details>
### Cohort 3
`r knitr::include_url("https://www.youtube.com/embed/JPDAWd4Pi7U")`
<details>
<summary>Meeting chat log</summary>
```
00:22:46 Brendan Lam: Nope 🙁
00:24:41 Federica Gazzelloni: more info here: https://engineering-shiny.org/common-app-caveats.html?q=R6#using-r6-as-data-storage
00:29:07 Federica Gazzelloni: video: https://www.youtube.com/watch?v=JkacZOrB1QY&list=PL3x6DOfs2NGh-XM69f20HXT7QXCuQPZxB&index=12
01:06:16 Federica Gazzelloni: https://shiny.rstudio.com/reference/shiny/1.3.0/reactiveVal.html
01:12:11 Brendan Lam: my wifi was unstable so ill have to go back and rewatch some of this, but thank you Lucy for presenting!
01:12:27 Brendan Lam: Bye!
```
</details>
`r knitr::include_url("https://www.youtube.com/embed/FGexkKxQ_wA")`
<details>
<summary>Meeting chat log</summary>
```
00:10:15 LUCIO ENRIQUE CORNEJO RAMÍREZ: Hi, it's Lucio :)
00:35:24 Federica Gazzelloni: https://shiny.rstudio.com/articles/isolation.html
00:40:59 Federica Gazzelloni: that’s nice: https://shiny.rstudio.com/gallery/isolate-demo.html
00:41:13 Federica Gazzelloni: let's see how it does
00:50:45 Oluwafemi Oyedele: Thank you!!!
00:50:59 LUCIO ENRIQUE CORNEJO RAMÍREZ: Thanks!
```
</details>
### Cohort 4
`r knitr::include_url("https://www.youtube.com/embed/BiliSGguMAk")`
<details>
<summary>Meeting chat log</summary>
```
00:03:22 Matthew: Hi everyone,
We will start in 7 - 10 mins.
00:03:35 Lydia Gibson: Hello
00:03:53 Matthew: Hello
00:07:03 Lydia Gibson: We need to update the dates on the volunteers sheet. I most likely won’t be able to attend on 5/16 so I’m not sure which chapter to sign up to present next
00:07:19 Lucio Cornejo: Hello
00:07:24 Lydia Gibson: Hello
00:07:55 Matthew: Hello
00:10:05 Lucio Cornejo: hi matthew
00:10:38 Lucio Cornejo: Hello Trevin
00:11:30 Lucio Cornejo: Hello Matthew
00:48:59 Lydia Gibson: Ntd for another meeting. See you all next week!
00:55:35 Lucio Cornejo: Thanks for the presentation. See you, everyone
```
</details>
### Cohort 5
`r knitr::include_url("https://www.youtube.com/embed/URL")`
<details>
<summary>Meeting chat log</summary>
```
LOG
```
</details>