Debian Codegraph @

R/reactives.R

raw
1 #' @include utils.R
2 NULL
3
4 Dependents <- R6Class(
5 'Dependents',
6 portable = FALSE,
7 class = FALSE,
8 public = list(
9 .reactId = character(0),
10 .dependents = 'Map',
11
12 initialize = function(reactId = NULL) {
13 .reactId <<- reactId
14 .dependents <<- Map$new()
15 },
16 # ... ignored, use to be depLabel and depId, not used anymore
17 register = function(...) {
18 ctx <- getCurrentContext()
19 if (!.dependents$containsKey(ctx$id)) {
20
21 # must wrap in if statement as ctx react id could be NULL
22 # if options(shiny.suppressMissingContextError = TRUE)
23 if (is.character(.reactId) && is.character(ctx$.reactId)) {
24 rLog$dependsOn(ctx$.reactId, .reactId, ctx$id, ctx$.domain)
25 }
26
27 if (ctx$isWeak()) {
28 .dependents$set(ctx$id, rlang::new_weakref(ctx))
29 } else {
30 .dependents$set(ctx$id, ctx)
31 }
32
33 ctx$onInvalidate(function() {
34 rLog$dependsOnRemove(ctx$.reactId, .reactId, ctx$id, ctx$.domain)
35 .dependents$remove(ctx$id)
36 })
37 }
38 },
39 # at times, the context is run in a ctx$onInvalidate(...) which has no runtime context
40 invalidate = function(log = TRUE) {
41 if (isTRUE(log)) {
42
43 domain <- getDefaultReactiveDomain()
44 rLog$invalidateStart(.reactId, NULL, "other", domain)
45 on.exit(
46 rLog$invalidateEnd(.reactId, NULL, "other", domain),
47 add = TRUE
48 )
49 }
50 lapply(
51 .dependents$values(sort = TRUE),
52 function(ctx) {
53 if (rlang::is_weakref(ctx)) {
54 ctx <- rlang::wref_key(ctx)
55 if (is.null(ctx)) {
56 # Can get here if weakref target was GC'd
57 return()
58 }
59 }
60 ctx$invalidate()
61 NULL
62 }
63 )
64 }
65 )
66 )
67
68
69 # ReactiveVal ---------------------------------------------------------------
70
71 ReactiveVal <- R6Class(
72 'ReactiveVal',
73 portable = FALSE,
74 private = list(
75 reactId = character(0),
76 value = NULL,
77 label = NULL,
78 frozen = FALSE,
79 dependents = NULL
80 ),
81 public = list(
82 .isRecordingOtel = FALSE, # Needs to be set by Shiny
83 .otelLabel = NULL, # Needs to be set by Shiny
84 .otelAttrs = NULL, # Needs to be set by Shiny
85
86 initialize = function(value, label = NULL) {
87 reactId <- nextGlobalReactId()
88 private$reactId <- reactId
89 private$value <- value
90 private$label <- label
91 private$dependents <- Dependents$new(reactId = private$reactId)
92
93 domain <- getDefaultReactiveDomain()
94 rLog$define(private$reactId, value, private$label, type = "reactiveVal", domain)
95 .otelLabel <<- otel_log_label_set_reactive_val(private$label, domain = domain)
96 },
97 get = function() {
98 private$dependents$register()
99
100 if (private$frozen)
101 reactiveStop()
102
103 private$value
104 },
105 set = function(value) {
106 if (identical(private$value, value)) {
107 return(invisible(FALSE))
108 }
109
110 domain <- getDefaultReactiveDomain()
111 if ((!is.null(domain)) && .isRecordingOtel) {
112 otel_log(
113 .otelLabel,
114 severity = "info",
115 attributes = c(private$.otelAttrs, otel_session_id_attrs(domain))
116 )
117 }
118 rLog$valueChange(private$reactId, value, domain)
119 private$value <- value
120 private$dependents$invalidate()
121 invisible(TRUE)
122 },
123 freeze = function(session = getDefaultReactiveDomain()) {
124 checkReactiveDomain(session)
125 rLog$freezeReactiveVal(private$reactId, session)
126 session$onFlushed(function() {
127 self$thaw(session)
128 })
129 private$frozen <- TRUE
130 },
131 thaw = function(session = getDefaultReactiveDomain()) {
132 rLog$thawReactiveVal(private$reactId, session)
133 private$frozen <- FALSE
134 },
135 isFrozen = function() {
136 private$frozen
137 },
138 format = function(...) {
139 # capture.output(print()) is necessary because format() doesn't
140 # necessarily return a character vector, e.g. data.frame.
141 label <- utils::capture.output(print(base::format(private$value, ...)))
142 if (length(label) == 1) {
143 paste0("reactiveVal: ", label)
144 } else {
145 c("reactiveVal:", label)
146 }
147 }
148 )
149 )
150
151 #' Create a (single) reactive value
152 #'
153 #' The `reactiveVal` function is used to construct a "reactive value"
154 #' object. This is an object used for reading and writing a value, like a
155 #' variable, but with special capabilities for reactive programming. When you
156 #' read the value out of a reactiveVal object, the calling reactive expression
157 #' takes a dependency, and when you change the value, it notifies any reactives
158 #' that previously depended on that value.
159 #'
160 #' `reactiveVal` is very similar to [reactiveValues()], except
161 #' that the former is for a single reactive value (like a variable), whereas the
162 #' latter lets you conveniently use multiple reactive values by name (like a
163 #' named list of variables). For a one-off reactive value, it's more natural to
164 #' use `reactiveVal`. See the Examples section for an illustration.
165 #'
166 #' @param value An optional initial value.
167 #' @param label An optional label, for debugging purposes (see
168 #' [reactlog()]). If missing, a label will be automatically
169 #' created.
170 #'
171 #' @return A function. Call the function with no arguments to (reactively) read
172 #' the value; call the function with a single argument to set the value.
173 #'
174 #' @examples
175 #'
176 #' \dontrun{
177 #'
178 #' # Create the object by calling reactiveVal
179 #' r <- reactiveVal()
180 #'
181 #' # Set the value by calling with an argument
182 #' r(10)
183 #'
184 #' # Read the value by calling without arguments
185 #' r()
186 #'
187 #' }
188 #'
189 #' ## Only run examples in interactive R sessions
190 #' if (interactive()) {
191 #'
192 #' ui <- fluidPage(
193 #' actionButton("minus", "-1"),
194 #' actionButton("plus", "+1"),
195 #' br(),
196 #' textOutput("value")
197 #' )
198 #'
199 #' # The comments below show the equivalent logic using reactiveValues()
200 #' server <- function(input, output, session) {
201 #' value <- reactiveVal(0) # rv <- reactiveValues(value = 0)
202 #'
203 #' observeEvent(input$minus, {
204 #' newValue <- value() - 1 # newValue <- rv$value - 1
205 #' value(newValue) # rv$value <- newValue
206 #' })
207 #'
208 #' observeEvent(input$plus, {
209 #' newValue <- value() + 1 # newValue <- rv$value + 1
210 #' value(newValue) # rv$value <- newValue
211 #' })
212 #'
213 #' output$value <- renderText({
214 #' value() # rv$value
215 #' })
216 #' }
217 #'
218 #' shinyApp(ui, server)
219 #'
220 #' }
221 #'
222 #' @export
223 reactiveVal <- function(value = NULL, label = NULL) {
224 call_srcref <- get_call_srcref()
225 if (missing(label)) {
226 label <- rassignSrcrefToLabel(
227 call_srcref,
228 defaultLabel = paste0("reactiveVal", createUniqueId(4))
229 )
230 }
231
232 rv <- ReactiveVal$new(value, label)
233 if (!is.null(call_srcref)) {
234 rv$.otelAttrs <- otel_srcref_attributes(call_srcref, fn_name = "reactiveVal")
235 }
236
237 ret <- structure(
238 function(x) {
239 if (missing(x)) {
240 rv$get()
241 } else {
242 force(x)
243 rv$set(x)
244 }
245 },
246 class = c("reactiveVal", "reactive", "function"),
247 label = label,
248 .impl = rv
249 )
250
251 if (has_otel_collect("reactivity")) {
252 ret <- enable_otel_reactive_val(ret)
253 }
254
255 ret
256 }
257
258 #' @rdname freezeReactiveValue
259 #' @export
260 freezeReactiveVal <- function(x) {
261 if (getOption("shiny.deprecation.messages", TRUE) && getOption("shiny.deprecation.messages.freeze", TRUE)) {
262 rlang::warn(
263 "freezeReactiveVal() is soft-deprecated, and may be removed in a future version of Shiny. (See https://github.com/rstudio/shiny/issues/3063)",
264 .frequency = "once", .frequency_id = "freezeReactiveVal")
265 }
266
267 domain <- getDefaultReactiveDomain()
268 checkReactiveDomain(domain)
269
270 if (!inherits(x, "reactiveVal")) {
271 rlang::abort("`x` must be a reactiveVal.")
272 }
273
274 attr(x, ".impl", exact = TRUE)$freeze(domain)
275 invisible()
276 }
277
278 checkReactiveDomain <- function(x) {
279 if (is.null(x)) {
280 rlang::abort("Can't freeze reactive values without a reactive domain.")
281 }
282 }
283
284
285 #' @export
286 format.reactiveVal <- function(x, ...) {
287 attr(x, ".impl", exact = TRUE)$format(...)
288 }
289
290 # Attempts to extract the variable name that the reactiveVal object is being
291 # assigned to (e.g. for `a <- reactiveVal()`, the result should be "a"). This
292 # is a fragile, error-prone operation, so we default to a random label if
293 # necessary.
294 rassignSrcrefToLabel <- function(
295 srcref,
296 defaultLabel,
297 fnName = "([a-zA-Z0-9_.]+)"
298 ) {
299
300 if (is.null(srcref))
301 return(defaultLabel)
302
303 srcfile <- attr(srcref, "srcfile", exact = TRUE)
304 if (is.null(srcfile))
305 return(defaultLabel)
306
307 src <- getSrcfileLines(srcfile, srcref)
308 lines <- src$lines
309 line_num <- src$line_num
310
311 if (is.null(lines))
312 return(defaultLabel)
313
314 # When pasting at the Console, srcfile$lines is not split
315 if (length(lines) == 1) {
316 lines <- strsplit(lines, "\n")[[1]]
317 }
318
319 if (length(lines) < line_num) {
320 return(defaultLabel)
321 }
322
323 firstLine <- substring(lines[line_num], srcref[2] - 1)
324
325 m <- regexec(
326 # Require the first assignment within the line
327 paste0("^\\s*([^[:space:]]+)\\s*(<<-|<-|=)\\s*", fnName, "\\b"),
328 firstLine
329 )
330 if (m[[1]][1] == -1) {
331 return(defaultLabel)
332 }
333
334 sym <- regmatches(firstLine, m)[[1]][2]
335 res <- try(parse(text = sym), silent = TRUE)
336 if (inherits(res, "try-error"))
337 return(defaultLabel)
338
339 if (length(res) != 1)
340 return(defaultLabel)
341
342 return(as.character(res))
343 }
344
345
346 # ReactiveValues ------------------------------------------------------------
347
348 ReactiveValues <- R6Class(
349 'ReactiveValues',
350 portable = FALSE,
351 public = list(
352 # For debug purposes
353 .reactId = character(0),
354 .label = character(0),
355 .values = 'Map',
356 .metadata = 'Map',
357 # A map of Dependents objects, one for each key
358 .dependents = 'Map',
359 # Dependents for the list of all names, including hidden
360 .namesDeps = 'Dependents',
361 # Dependents for all values, including hidden
362 .allValuesDeps = 'Dependents',
363 # Dependents for all values
364 .valuesDeps = 'Dependents',
365 .dedupe = logical(0),
366 # Key, asList(), or names() have been retrieved
367 .hasRetrieved = list(),
368 # All names, in insertion order. The names are also stored in the .values
369 # object, but it does not preserve order.
370 .nameOrder = character(0),
371
372 .isRecordingOtel = FALSE, # Needs to be set by Shiny
373 .otelAttrs = NULL, # Needs to be set by Shiny
374
375
376 initialize = function(
377 dedupe = TRUE,
378 label = paste0('reactiveValues', p_randomInt(1000, 10000))
379 ) {
380 .reactId <<- nextGlobalReactId()
381 .label <<- label
382 .values <<- Map$new()
383 .metadata <<- Map$new()
384 .dependents <<- Map$new()
385 .hasRetrieved <<- list(names = FALSE, asListAll = FALSE, asList = FALSE)
386 .namesDeps <<- Dependents$new(reactId = rLog$namesIdStr(.reactId))
387 .allValuesDeps <<- Dependents$new(reactId = rLog$asListAllIdStr(.reactId))
388 .valuesDeps <<- Dependents$new(reactId = rLog$asListIdStr(.reactId))
389 .dedupe <<- dedupe
390 },
391
392 get = function(key) {
393 # get value right away to use for logging
394 keyValue <- .values$get(key)
395
396 if (!.dependents$containsKey(key)) {
397 # If we got here, this is the first time someone has tried to access
398 # this key.
399 rLog$defineKey(.reactId, keyValue, key, .label, getCurrentContext()$.domain)
400
401 reactKeyId <- rLog$keyIdStr(.reactId, key)
402 .dependents$set(key, Dependents$new(reactKeyId))
403 }
404
405 # Register the "downstream" reactive which is accessing this value, so
406 # that we know to invalidate them when this value changes.
407 .dependents$get(key)$register()
408
409 if (isFrozen(key))
410 reactiveStop()
411
412 keyValue
413 },
414
415 set = function(key, value, force = FALSE) {
416 # if key exists
417 # if it is the same value, return
418 #
419 # update value of `key`
420 #
421 # if key exists
422 # if `key` has been read,
423 # log `update key`
424 # ## (invalidate key later in code)
425 # else # if new key
426 # if `names()` have been read,
427 # log `update names()`
428 # invalidate `names()`
429 #
430 # if hidden
431 # if asListAll has been read,
432 # log `update asList(all.names = TRUE)`
433 # invalidate `asListAll`
434 # else # not hidden
435 # if asList has been read,
436 # log `update asList()`
437 # invalidate `asList`
438 #
439 # update value of `key`
440 # invalidate all deps of `key`
441
442 domain <- getDefaultReactiveDomain()
443 hidden <- substr(key, 1, 1) == "."
444
445 key_exists <- .values$containsKey(key)
446
447 if (key_exists && !isTRUE(force) && .dedupe && identical(.values$get(key), value)) {
448 return(invisible())
449 }
450
451 if ((!is.null(domain)) && .isRecordingOtel) {
452 if (
453 # Any reactiveValues (other than input or clientData) are fair game
454 !(.label == "input" || .label == "clientData") ||
455 # Do not include updates to input or clientData unless _some_ reactivity has occured
456 !is.null(domain$userData[["_otel_has_reactive_cleanup"]])
457 ) {
458 otel_log(
459 otel_log_label_set_reactive_values(.label, key, domain = domain),
460 severity = "info",
461 attributes = c(.otelAttrs, otel_session_id_attrs(domain))
462 )
463 }
464 }
465
466 # If it's new, append key to the name order
467 if (!key_exists) {
468 .nameOrder[length(.nameOrder) + 1] <<- key
469 }
470
471 # set the value for better logging
472 .values$set(key, value)
473
474 # key has been depended upon
475 if (.dependents$containsKey(key)) {
476 rLog$valueChangeKey(.reactId, key, value, domain)
477 .dependents$get(key)$invalidate()
478 }
479
480 # only invalidate if there are deps
481 if (!key_exists && isTRUE(.hasRetrieved$names)) {
482 rLog$valueChangeNames(.reactId, .values$keys(), domain)
483 .namesDeps$invalidate()
484 }
485
486 if (hidden) {
487 if (isTRUE(.hasRetrieved$asListAll)) {
488 rLog$valueChangeAsListAll(.reactId, .values$values(), domain)
489 .allValuesDeps$invalidate()
490 }
491 } else {
492 if (isTRUE(.hasRetrieved$asList)) {
493 react_vals <- .values$values()
494 react_vals <- react_vals[!grepl("^\\.", base::names(react_vals))]
495 # leave as is. both object would be registered to the listening object
496 rLog$valueChangeAsList(.reactId, react_vals, domain)
497 .valuesDeps$invalidate()
498 }
499 }
500
501 invisible()
502 },
503
504 mset = function(lst) {
505 lapply(base::names(lst),
506 function(name) {
507 self$set(name, lst[[name]])
508 })
509 },
510
511 names = function() {
512 if (!isTRUE(.hasRetrieved$names)) {
513 domain <- getDefaultReactiveDomain()
514 rLog$defineNames(.reactId, .nameOrder, .label, domain)
515 .hasRetrieved$names <<- TRUE
516 }
517 .namesDeps$register()
518 return(.nameOrder)
519 },
520
521 # Get a metadata value. Does not trigger reactivity.
522 getMeta = function(key, metaKey) {
523 # Make sure to use named (not numeric) indexing into list.
524 metaKey <- as.character(metaKey)
525 .metadata$get(key)[[metaKey]]
526 },
527
528 # Set a metadata value. Does not trigger reactivity.
529 setMeta = function(key, metaKey, value) {
530 # Make sure to use named (not numeric) indexing into list.
531 metaKey <- as.character(metaKey)
532
533 if (!.metadata$containsKey(key)) {
534 .metadata$set(key, list())
535 }
536
537 m <- .metadata$get(key)
538 m[[metaKey]] <- value
539 .metadata$set(key, m)
540 },
541
542 # Mark a value as frozen If accessed while frozen, a shiny.silent.error will
543 # be thrown.
544 freeze = function(key, invalidate = FALSE) {
545 domain <- getDefaultReactiveDomain()
546 rLog$freezeReactiveKey(.reactId, key, domain)
547 setMeta(key, "frozen", TRUE)
548
549 if (invalidate) {
550 # Force an invalidation
551 self$set(key, NULL, force = TRUE)
552 }
553 },
554
555 thaw = function(key) {
556 domain <- getDefaultReactiveDomain()
557 rLog$thawReactiveKey(.reactId, key, domain)
558 setMeta(key, "frozen", NULL)
559 },
560
561 isFrozen = function(key) {
562 isTRUE(getMeta(key, "frozen"))
563 },
564
565 toList = function(all.names=FALSE) {
566 listValue <- .values$mget(.nameOrder)
567 if (!all.names) {
568 listValue <- listValue[!grepl("^\\.", base::names(listValue))]
569 }
570 if (all.names) {
571 if (!isTRUE(.hasRetrieved$asListAll)) {
572 domain <- getDefaultReactiveDomain()
573 rLog$defineAsListAll(.reactId, listValue, .label, domain)
574 .hasRetrieved$asListAll <<- TRUE
575 }
576 .allValuesDeps$register()
577 }
578
579 if (!isTRUE(.hasRetrieved$asList)) {
580 domain <- getDefaultReactiveDomain()
581 # making sure the value being recorded is with `all.names = FALSE`
582 rLog$defineAsList(.reactId, listValue[!grepl("^\\.", base::names(listValue))], .label, domain)
583 .hasRetrieved$asList <<- TRUE
584 }
585 .valuesDeps$register()
586
587 return(listValue)
588 }
589
590 )
591 )
592
593
594 # reactivevalues ------------------------------------------------------------
595 # S3 wrapper class for ReactiveValues reference class
596
597 #' Create an object for storing reactive values
598 #'
599 #' This function returns an object for storing reactive values. It is similar to
600 #' a list, but with special capabilities for reactive programming. When you read
601 #' a value from it, the calling reactive expression takes a reactive dependency
602 #' on that value, and when you write to it, it notifies any reactive functions
603 #' that depend on that value. Note that values taken from the reactiveValues
604 #' object are reactive, but the reactiveValues object itself is not.
605 #'
606 #' @examples
607 #' # Create the object with no values
608 #' values <- reactiveValues()
609 #'
610 #' # Assign values to 'a' and 'b'
611 #' values$a <- 3
612 #' values[['b']] <- 4
613 #'
614 #' \dontrun{
615 #' # From within a reactive context, you can access values with:
616 #' values$a
617 #' values[['a']]
618 #' }
619 #'
620 #' # If not in a reactive context (e.g., at the console), you can use isolate()
621 #' # to retrieve the value:
622 #' isolate(values$a)
623 #' isolate(values[['a']])
624 #'
625 #' # Set values upon creation
626 #' values <- reactiveValues(a = 1, b = 2)
627 #' isolate(values$a)
628 #'
629 #' @param ... Objects that will be added to the reactivevalues object. All of
630 #' these objects must be named.
631 #'
632 #' @seealso [isolate()] and [is.reactivevalues()].
633 #' @export
634 reactiveValues <- function(...) {
635 args <- list2(...)
636 if ((length(args) > 0) && (is.null(names(args)) || any(names(args) == "")))
637 rlang::abort("All arguments passed to reactiveValues() must be named.")
638
639 values <- .createReactiveValues(ReactiveValues$new(), withOtel = FALSE)
640
641 # Use .subset2() instead of [[, to avoid method dispatch
642 impl <- .subset2(values, 'impl')
643
644 call_srcref <- get_call_srcref()
645 if (!is.null(call_srcref)) {
646 impl$.label <- rassignSrcrefToLabel(
647 call_srcref,
648 # Pass through the random default label created in ReactiveValues$new()
649 defaultLabel = impl$.label
650 )
651
652 impl$.otelAttrs <- otel_srcref_attributes(call_srcref, fn_name = "reactiveValues")
653 }
654
655 impl$mset(args)
656
657 # Add otel collection after `$mset()` so that we don't log the initial values
658 # Add otel collection after `.label` so that any logging uses the correct label
659 values <- maybeAddReactiveValuesOtel(values)
660
661 values
662 }
663
664 checkName <- function(x) {
665 if (!is.character(x) || length(x) != 1) {
666 rlang::abort("Must use single string to index into reactivevalues.")
667 }
668 }
669
670 # Create a reactivevalues object
671 #
672 # @param values A ReactiveValues object
673 # @param readonly Should this object be read-only?
674 # @param ns A namespace function (either `identity` or `NS(namespace)`)
675 # @param withOtel Should otel collection be attempted?
676 .createReactiveValues <- function(values = NULL, readonly = FALSE,
677 ns = identity, withOtel = TRUE) {
678
679 ret <- structure(
680 list(
681 impl = values,
682 readonly = readonly,
683 ns = ns
684 ),
685 class='reactivevalues'
686 )
687
688 if (withOtel) {
689 ret <- maybeAddReactiveValuesOtel(ret)
690 }
691
692 ret
693 }
694
695 maybeAddReactiveValuesOtel <- function(x) {
696 if (!has_otel_collect("reactivity")) {
697 return(x)
698 }
699
700 enable_otel_reactive_values(x)
701 }
702
703 #' @export
704 print.reactivevalues <- function(x, ...) {
705 impl <- .subset2(x, "impl")
706 cat_line("<ReactiveValues>")
707 cat_line(" Values: ", paste0(impl$.values$keys(sort = TRUE), collapse = ", "))
708 cat_line(" Readonly: ", .subset2(x, "readonly"))
709 }
710
711 #' Checks whether an object is a reactivevalues object
712 #'
713 #' Checks whether its argument is a reactivevalues object.
714 #'
715 #' @param x The object to test.
716 #' @seealso [reactiveValues()].
717 #' @export
718 is.reactivevalues <- function(x) inherits(x, 'reactivevalues')
719
720 #' @export
721 `$.reactivevalues` <- function(x, name) {
722 checkName(name)
723
724 if (!hasCurrentContext()) {
725 rlang::abort(c(
726 paste0("Can't access reactive value '", name, "' outside of reactive consumer."),
727 i = "Do you need to wrap inside reactive() or observe()?"
728 ))
729 }
730
731 .subset2(x, 'impl')$get(.subset2(x, 'ns')(name))
732 }
733
734 #' @export
735 `[[.reactivevalues` <- `$.reactivevalues`
736
737 #' @export
738 `$<-.reactivevalues` <- function(x, name, value) {
739 if (.subset2(x, 'readonly')) {
740 rlang::abort(paste0("Can't modify read-only reactive value '", name, "'"))
741 }
742 checkName(name)
743 .subset2(x, 'impl')$set(.subset2(x, 'ns')(name), value)
744 x
745 }
746
747 #' @export
748 `[[<-.reactivevalues` <- `$<-.reactivevalues`
749
750 #' @export
751 `[.reactivevalues` <- function(values, name) {
752 rlang::abort("Can't index reactivevalues with `[`.")
753 }
754
755 #' @export
756 `[<-.reactivevalues` <- function(values, name, value) {
757 rlang::abort("Can't index reactivevalues with `[`.")
758 }
759
760 #' @export
761 names.reactivevalues <- function(x) {
762 prefix <- .subset2(x, 'ns')("")
763 results <- .subset2(x, 'impl')$names()
764 if (nzchar(prefix)) {
765 results <- results[substring(results, 1, nchar(prefix)) == prefix]
766 results <- substring(results, nchar(prefix) + 1)
767 }
768 results
769 }
770
771 #' @export
772 `names<-.reactivevalues` <- function(x, value) {
773 rlang::abort("Can't assign names to reactivevalues.")
774 }
775
776 #' @export
777 as.list.reactivevalues <- function(x, all.names=FALSE, ...) {
778 shinyDeprecated(
779 "0.4.0", "as.list.reactivevalues()", "reactiveValuesToList()",
780 details = "Please see ?reactiveValuesToList for more information."
781 )
782
783 reactiveValuesToList(x, all.names)
784 }
785
786 #' Convert a reactivevalues object to a list
787 #'
788 #' This function does something similar to what you might want or expect
789 #' [base::as.list()] to do. The difference is that the calling context will take
790 #' dependencies on every object in the `reactivevalue`s object. To avoid taking
791 #' dependencies on all the objects, you can wrap the call with [isolate()].
792 #'
793 #' @param x A `reactivevalues` object.
794 #' @param all.names If `TRUE`, include objects with a leading dot. If `FALSE`
795 #' (the default) don't include those objects.
796 #' @examples
797 #' values <- reactiveValues(a = 1)
798 #' \dontrun{
799 #' reactiveValuesToList(values)
800 #' }
801 #'
802 #' # To get the objects without taking dependencies on them, use isolate().
803 #' # isolate() can also be used when calling from outside a reactive context (e.g.
804 #' # at the console)
805 #' isolate(reactiveValuesToList(values))
806 #' @export
807 reactiveValuesToList <- function(x, all.names=FALSE) {
808 # Default case
809 res <- .subset2(x, 'impl')$toList(all.names)
810
811 prefix <- .subset2(x, 'ns')("")
812 # Special handling for namespaces
813 if (nzchar(prefix)) {
814 fullNames <- names(res)
815
816 # Filter out items that match namespace
817 fullNames <- fullNames[substring(fullNames, 1, nchar(prefix)) == prefix]
818 res <- res[fullNames]
819
820 # Remove namespace prefix
821 names(res) <- substring(fullNames, nchar(prefix) + 1)
822 }
823
824 res
825 }
826
827 # This function is needed because str() on a reactivevalues object will call
828 # [[.reactivevalues(), which will give an error when it tries to access
829 # x[['impl']].
830 #' @export
831 str.reactivevalues <- function(object, indent.str = " ", ...) {
832 utils::str(unclass(object), indent.str = indent.str, ...)
833 # Need to manually print out the class field,
834 cat(indent.str, '- attr(*, "class")=', sep = "")
835 utils::str(class(object))
836 }
837
838
839 #' Freeze a reactive value
840 #'
841 #' These functions freeze a [reactiveVal()], or an element of a
842 #' [reactiveValues()]. If the value is accessed while frozen, a
843 #' "silent" exception is raised and the operation is stopped. This is the same
844 #' thing that happens if `req(FALSE)` is called. The value is thawed
845 #' (un-frozen; accessing it will no longer raise an exception) when the current
846 #' reactive domain is flushed. In a Shiny application, this occurs after all of
847 #' the observers are executed. **NOTE:** We are considering deprecating
848 #' `freezeReactiveVal`, and `freezeReactiveValue` except when `x` is `input`.
849 #' If this affects your app, please let us know by leaving a comment on
850 #' [this GitHub issue](https://github.com/rstudio/shiny/issues/3063).
851 #'
852 #' @param x For `freezeReactiveValue`, a [reactiveValues()]
853 #' object (like `input`); for `freezeReactiveVal`, a
854 #' [reactiveVal()] object.
855 #' @param name The name of a value in the [reactiveValues()] object.
856 #'
857 #' @seealso [req()]
858 #' @examples
859 #' ## Only run this examples in interactive R sessions
860 #' if (interactive()) {
861 #'
862 #' ui <- fluidPage(
863 #' selectInput("data", "Data Set", c("mtcars", "pressure")),
864 #' checkboxGroupInput("cols", "Columns (select 2)", character(0)),
865 #' plotOutput("plot")
866 #' )
867 #'
868 #' server <- function(input, output, session) {
869 #' observe({
870 #' data <- get(input$data)
871 #' # Sets a flag on input$cols to essentially do req(FALSE) if input$cols
872 #' # is accessed. Without this, an error will momentarily show whenever a
873 #' # new data set is selected.
874 #' freezeReactiveValue(input, "cols")
875 #' updateCheckboxGroupInput(session, "cols", choices = names(data))
876 #' })
877 #'
878 #' output$plot <- renderPlot({
879 #' # When a new data set is selected, input$cols will have been invalidated
880 #' # above, and this will essentially do the same as req(FALSE), causing
881 #' # this observer to stop and raise a silent exception.
882 #' cols <- input$cols
883 #' data <- get(input$data)
884 #'
885 #' if (length(cols) == 2) {
886 #' plot(data[[ cols[1] ]], data[[ cols[2] ]])
887 #' }
888 #' })
889 #' }
890 #'
891 #' shinyApp(ui, server)
892 #' }
893 #' @export
894 freezeReactiveValue <- function(x, name) {
895 domain <- getDefaultReactiveDomain()
896 checkReactiveDomain(domain)
897
898 domain$freezeValue(x, name)
899 invisible()
900 }
901
902
903 # Observable ----------------------------------------------------------------
904
905 Observable <- R6Class(
906 'Observable',
907 portable = FALSE,
908 public = list(
909 .reactId = character(0),
910 .origFunc = 'function',
911 .func = 'function',
912 .label = character(0),
913 .domain = NULL,
914 .dependents = 'Dependents',
915 .invalidated = logical(0),
916 .running = logical(0),
917 .value = NULL,
918 .error = FALSE,
919 .visible = logical(0),
920 .execCount = integer(0),
921 .mostRecentCtxId = character(0),
922 .ctx = 'Context',
923
924 .isRecordingOtel = FALSE, # Needs to be set by Shiny
925 .otelLabel = NULL, # Needs to be set by Shiny
926 .otelAttrs = NULL, # Needs to be set by Shiny
927
928 initialize = function(func, label = deparse(substitute(func)),
929 domain = getDefaultReactiveDomain(),
930 ..stacktraceon = TRUE) {
931 if (length(formals(func)) > 0)
932 rlang::abort(c(
933 "Can't make a reactive expression from a function that takes arguments.",
934 "Only functions without parameters can become reactive expressions."
935 ))
936
937 # This is to make sure that the function labels that show in the profiler
938 # and in stack traces doesn't contain whitespace. See
939 # https://github.com/rstudio/profvis/issues/58
940 if (grepl("\\s", label, perl = TRUE)) {
941 funcLabel <- "<reactive>"
942 } else {
943 funcLabel <- paste0("<reactive:", label, ">")
944 }
945
946 .reactId <<- nextGlobalReactId()
947 .origFunc <<- func
948 .func <<- wrapFunctionLabel(func, funcLabel,
949 ..stacktraceon = ..stacktraceon)
950 .label <<- label
951 .domain <<- domain
952 .dependents <<- Dependents$new(reactId = .reactId)
953 .invalidated <<- TRUE
954 .running <<- FALSE
955 .execCount <<- 0L
956 .mostRecentCtxId <<- ""
957 .ctx <<- NULL
958 rLog$define(.reactId, .value, .label, type = "observable", .domain)
959 },
960 getValue = function() {
961 .dependents$register()
962
963 if (.invalidated || .running) {
964 ..stacktraceoff..(
965 self$.updateValue()
966 )
967 }
968
969 if (.error) {
970 stop(.value)
971 }
972
973 if (.visible)
974 .value
975 else
976 invisible(.value)
977 },
978 format = function() {
979 simpleExprToFunction(fn_body(.origFunc), "reactive")
980 },
981 .updateValue = function() {
982 ctx <- Context$new(
983 .domain,
984 .label,
985 type = 'observable',
986 prevId = .mostRecentCtxId,
987 reactId = .reactId,
988 weak = TRUE,
989 otel_info = ctx_otel_info_obj(
990 isRecordingOtel = .isRecordingOtel,
991 otelLabel = .otelLabel,
992 otelAttrs = c(.otelAttrs, otel_session_id_attrs(.domain))
993 )
994 )
995 .mostRecentCtxId <<- ctx$id
996
997 # A Dependency object will have a weak reference to the context, which
998 # doesn't prevent it from being GC'd. However, as long as this
999 # Observable object is reachable and not invalidated, we need to make
1000 # sure the context isn't GC'd. To do that we need a strong reference to
1001 # the context.
1002 .ctx <<- ctx
1003
1004 ctx$onInvalidate(function() {
1005 .invalidated <<- TRUE
1006 .value <<- NULL # Value can be GC'd, it won't be read once invalidated
1007 .dependents$invalidate(log = FALSE)
1008 .ctx <<- NULL # No longer need to prevent the context from being GC'd.
1009 })
1010 .execCount <<- .execCount + 1L
1011
1012 .invalidated <<- FALSE
1013
1014 wasRunning <- .running
1015 .running <<- TRUE
1016 on.exit(.running <<- wasRunning)
1017
1018 ctx$run(function() {
1019 result <- withCallingHandlers(
1020
1021 {
1022 .error <<- FALSE
1023 withVisible(.func())
1024 },
1025
1026 error = function(cond) {
1027 if (.isRecordingOtel) {
1028 # `cond` is too early in the stack to be updated by `ctx`'s
1029 # `with_otel_span_context()` where it calls
1030 # `set_otel_exception_status_and_throw()` on eval error.
1031 # So we mark it as seen here.
1032 # When the error is re-thrown later, it won't be a _new_ error
1033 cond <- mark_otel_exception_as_seen(cond)
1034 }
1035
1036 # If an error occurs, we want to propagate the error, but we also
1037 # want to save a copy of it, so future callers of this reactive will
1038 # get the same error (i.e. the error is cached).
1039 .value <<- cond
1040 .error <<- TRUE
1041 .visible <<- FALSE
1042 }
1043 )
1044 .value <<- result$value
1045 .visible <<- result$visible
1046 })
1047 }
1048 )
1049 )
1050
1051 #' Create a reactive expression
1052 #'
1053 #' Wraps a normal expression to create a reactive expression. Conceptually, a
1054 #' reactive expression is a expression whose result will change over time.
1055 #'
1056 #' Reactive expressions are expressions that can read reactive values and call
1057 #' other reactive expressions. Whenever a reactive value changes, any reactive
1058 #' expressions that depended on it are marked as "invalidated" and will
1059 #' automatically re-execute if necessary. If a reactive expression is marked as
1060 #' invalidated, any other reactive expressions that recently called it are also
1061 #' marked as invalidated. In this way, invalidations ripple through the
1062 #' expressions that depend on each other.
1063 #'
1064 #' See the [Shiny tutorial](https://shiny.rstudio.com/tutorial/) for
1065 #' more information about reactive expressions.
1066 #'
1067 #' @param x For `is.reactive()`, an object to test. For `reactive()`, an
1068 #' expression. When passing in a [`rlang::quo()`]sure with `reactive()`,
1069 #' remember to use [`rlang::inject()`] to distinguish that you are passing in
1070 #' the content of your quosure, not the expression of the quosure.
1071 #' @template param-env
1072 #' @templateVar x x
1073 #' @templateVar env env
1074 #' @templateVar quoted quoted
1075 #' @template param-quoted
1076 #' @templateVar x x
1077 #' @templateVar quoted quoted
1078
1079 #' @param label A label for the reactive expression, useful for debugging.
1080 #' @param domain See [domains].
1081 #' @param ..stacktraceon Advanced use only. For stack manipulation purposes; see
1082 #' [stacktrace()].
1083 #' @param ... Not used.
1084 #' @return a function, wrapped in a S3 class "reactive"
1085 #'
1086 #' @examples
1087 #' library(rlang)
1088 #' values <- reactiveValues(A=1)
1089 #'
1090 #' reactiveB <- reactive({
1091 #' values$A + 1
1092 #' })
1093 #' # View the values from the R console with isolate()
1094 #' isolate(reactiveB())
1095 #' # 2
1096 #'
1097 #' # To store expressions for later conversion to reactive, use quote()
1098 #' myquo <- rlang::quo(values$A + 2)
1099 #' # Unexpected value! Sending a quosure directly will not work as expected.
1100 #' reactiveC <- reactive(myquo)
1101 #' # We'd hope for `3`, but instead we get the quosure that was supplied.
1102 #' isolate(reactiveC())
1103 #'
1104 #' # Instead, the quosure should be `rlang::inject()`ed
1105 #' reactiveD <- rlang::inject(reactive(!!myquo))
1106 #' isolate(reactiveD())
1107 #' # 3
1108 #'
1109 #' # (Legacy) Can use quoted expressions
1110 #' expr <- quote({ values$A + 3 })
1111 #' reactiveE <- reactive(expr, quoted = TRUE)
1112 #' isolate(reactiveE())
1113 #' # 4
1114 #'
1115 #' @export
1116 reactive <- function(
1117 x,
1118 env = parent.frame(),
1119 quoted = FALSE,
1120 ...,
1121 label = NULL,
1122 domain = getDefaultReactiveDomain(),
1123 ..stacktraceon = TRUE
1124 ) {
1125 check_dots_empty()
1126
1127 func <- installExprFunction(x, "func", env, quoted, wrappedWithLabel = FALSE)
1128 # Attach a label and a reference to the original user source for debugging
1129 userExpr <- fn_body(func)
1130 label <- exprToLabel(userExpr, "reactive", label)
1131
1132 o <- Observable$new(func, label, domain, ..stacktraceon = ..stacktraceon)
1133
1134 call_srcref <- get_call_srcref()
1135 if (!is.null(call_srcref)) {
1136 o$.otelAttrs <- otel_srcref_attributes(call_srcref, fn_name = "reactive")
1137 }
1138
1139 ret <- structure(
1140 o$getValue,
1141 observable = o,
1142 cacheHint = list(userExpr = zap_srcref(userExpr)),
1143 class = c("reactiveExpr", "reactive", "function")
1144 )
1145
1146 if (has_otel_collect("reactivity")) {
1147 ret <- enable_otel_reactive_expr(ret)
1148 }
1149
1150 ret
1151 }
1152
1153 # Given the srcref to a reactive expression, attempts to figure out what the
1154 # name of the reactive expression is. This isn't foolproof, as it literally
1155 # scans the line of code that started the reactive block and looks for something
1156 # that looks like assignment. If we fail, fall back to a default value (likely
1157 # the block of code in the body of the reactive).
1158 rexprSrcrefToLabel <- function(srcref, defaultLabel, fnName) {
1159 if (is.null(srcref))
1160 return(defaultLabel)
1161
1162 srcfile <- attr(srcref, "srcfile", exact = TRUE)
1163 if (is.null(srcfile))
1164 return(defaultLabel)
1165
1166 src <- getSrcfileLines(srcfile, srcref)
1167 lines <- src$lines
1168 line_num <- src$line_num
1169
1170 if (is.null(lines))
1171 return(defaultLabel)
1172
1173 # When pasting at the Console, srcfile$lines is not split
1174 if (length(lines) == 1) {
1175 lines <- strsplit(lines, "\n")[[1]]
1176 }
1177
1178 if (length(lines) < line_num) {
1179 return(defaultLabel)
1180 }
1181
1182 firstLine <- substring(lines[line_num], 1, srcref[2] - 1)
1183
1184 # Require the assignment to be parsed from the start
1185 m <- regexec(paste0("^(.*)(<<-|<-|=)\\s*", fnName, "\\s*\\($"), firstLine)
1186 if (m[[1]][1] == -1) {
1187 return(defaultLabel)
1188 }
1189 sym <- regmatches(firstLine, m)[[1]][2]
1190 res <- try(parse(text = sym), silent = TRUE)
1191 if (inherits(res, "try-error"))
1192 return(defaultLabel)
1193
1194 if (length(res) != 1)
1195 return(defaultLabel)
1196
1197 return(as.character(res))
1198 }
1199
1200 #' @export
1201 format.reactiveExpr <- function(x, ...) {
1202 attr(x, "observable", exact = TRUE)$format()
1203 }
1204
1205 #' @export
1206 print.reactive <- function(x, ...) {
1207 cat(paste(format(x), collapse = "\n"), "\n")
1208 }
1209
1210 #' @export
1211 #' @rdname reactive
1212 is.reactive <- function(x) {
1213 inherits(x, "reactive")
1214 }
1215
1216 # Return the number of times that a reactive expression or observer has been run
1217 execCount <- function(x) {
1218 if (inherits(x, "reactiveExpr"))
1219 return(attr(x, "observable", exact = TRUE)$.execCount)
1220 else if (inherits(x, 'Observer'))
1221 return(x$.execCount)
1222 else
1223 rlang::abort("Unexpected argument to execCount().")
1224 }
1225
1226 # Internal utility functions for extracting things out of reactives.
1227 reactive_get_value_func <- function(x) {
1228 attr(x, "observable", exact = TRUE)$.origFunc
1229 }
1230 reactive_get_domain <- function(x) {
1231 attr(x, "observable", exact = TRUE)$.domain
1232 }
1233
1234 # Observer ------------------------------------------------------------------
1235
1236 Observer <- R6Class(
1237 'Observer',
1238 portable = FALSE,
1239 public = list(
1240 .reactId = character(0),
1241 .func = 'function',
1242 .label = character(0),
1243 .domain = 'ANY',
1244 .priority = numeric(0),
1245 .autoDestroy = logical(0),
1246 # A function that, when invoked, unsubscribes the autoDestroy
1247 # listener (or NULL if autodestroy is disabled for this observer).
1248 # We must unsubscribe when this observer is destroyed, or else
1249 # the observer cannot be garbage collected until the session ends.
1250 .autoDestroyHandle = 'ANY',
1251 .invalidateCallbacks = list(),
1252 .execCount = integer(0),
1253 .onResume = 'function',
1254 .suspended = logical(0),
1255 .destroyed = logical(0),
1256 .prevId = character(0),
1257 .ctx = NULL,
1258
1259 .isRecordingOtel = FALSE, # Needs to be set by Shiny
1260 .otelLabel = NULL, # Needs to be set by Shiny
1261 .otelAttrs = NULL, # Needs to be set by Shiny
1262
1263 initialize = function(observerFunc, label, suspended = FALSE, priority = 0,
1264 domain = getDefaultReactiveDomain(),
1265 autoDestroy = TRUE, ..stacktraceon = TRUE) {
1266 if (length(formals(observerFunc)) > 0)
1267 rlang::abort(c(
1268 "Can't make an observer from a function that takes arguments.",
1269 "Only functions without arguments can become observers."
1270 ))
1271 if (grepl("\\s", label, perl = TRUE)) {
1272 funcLabel <- "<observer>"
1273 } else {
1274 funcLabel <- paste0("<observer:", label, ">")
1275 }
1276 .func <<- wrapFunctionLabel(observerFunc, funcLabel, ..stacktraceon = ..stacktraceon)
1277 .label <<- label
1278 .domain <<- domain
1279 .priority <<- normalizePriority(priority)
1280 .execCount <<- 0L
1281 .suspended <<- suspended
1282 .onResume <<- function() NULL
1283 .destroyed <<- FALSE
1284 .prevId <<- ''
1285
1286 .autoDestroy <<- FALSE
1287 .autoDestroyHandle <<- NULL
1288 setAutoDestroy(autoDestroy)
1289
1290 .reactId <<- nextGlobalReactId()
1291 rLog$defineObserver(.reactId, .label, .domain)
1292
1293 # Defer the first running of this until flushReact is called
1294 .createContext()$invalidate()
1295 },
1296 .createContext = function() {
1297 ctx <- Context$new(
1298 .domain,
1299 .label,
1300 type = 'observer',
1301 prevId = .prevId,
1302 reactId = .reactId,
1303 otel_info = ctx_otel_info_obj(
1304 isRecordingOtel = .isRecordingOtel,
1305 otelLabel = .otelLabel,
1306 otelAttrs = c(.otelAttrs, otel_session_id_attrs(.domain))
1307 )
1308 )
1309 .prevId <<- ctx$id
1310
1311 if (!is.null(.ctx)) {
1312 # If this happens, something went wrong.
1313 warning("Created a new context without invalidating previous context.")
1314 }
1315 # Store the context explicitly in the Observer object. This is necessary
1316 # to make sure that when the observer is destroyed, it also gets
1317 # invalidated. Otherwise the upstream reactive (on which the observer
1318 # depends) will hold a (indirect) reference to this context until the
1319 # reactive is invalidated, which may not happen immediately or at all.
1320 # This can lead to a memory leak (#1253).
1321 .ctx <<- ctx
1322
1323 ctx$onInvalidate(function() {
1324 # Context is invalidated, so we don't need to store a reference to it
1325 # anymore.
1326 .ctx <<- NULL
1327
1328 lapply(.invalidateCallbacks, function(invalidateCallback) {
1329 invalidateCallback()
1330 NULL
1331 })
1332
1333 continue <- function() {
1334 ctx$addPendingFlush(.priority)
1335 if (!is.null(.domain)) {
1336 .domain$incrementBusyCount()
1337 }
1338 }
1339
1340 if (.suspended == FALSE)
1341 continue()
1342 else
1343 .onResume <<- continue
1344 })
1345
1346 ctx$onFlush(function() {
1347
1348 hybrid_chain(
1349 {
1350 if (!.destroyed) {
1351 shinyCallingHandlers(run())
1352 }
1353 },
1354 catch = function(e) {
1355 # It's OK for shiny.silent.error errors to cause an observer to stop running
1356 # shiny.silent.error = function(e) NULL
1357 # validation = function(e) NULL,
1358 # shiny.output.cancel = function(e) NULL
1359
1360 if (cnd_inherits(e, "shiny.silent.error")) {
1361 return()
1362 }
1363
1364 printError(e)
1365 if (!is.null(.domain)) {
1366 .domain$unhandledError(e, close = TRUE)
1367 }
1368 },
1369 finally = .domain$decrementBusyCount
1370 )
1371 })
1372
1373 return(ctx)
1374 },
1375 run = function() {
1376 ctx <- .createContext()
1377 .execCount <<- .execCount + 1L
1378 ctx$run(.func)
1379 },
1380 onInvalidate = function(callback) {
1381 "Register a callback function to run when this observer is invalidated.
1382 No arguments will be provided to the callback function when it is
1383 invoked."
1384 .invalidateCallbacks <<- c(.invalidateCallbacks, callback)
1385 },
1386 setPriority = function(priority = 0) {
1387 "Change this observer's priority. Note that if the observer is currently
1388 invalidated, then the change in priority will not take effect until the
1389 next invalidation--unless the observer is also currently suspended, in
1390 which case the priority change will be effective upon resume."
1391 .priority <<- normalizePriority(priority)
1392 },
1393 setAutoDestroy = function(autoDestroy) {
1394 "Sets whether this observer should be automatically destroyed when its
1395 domain (if any) ends. If autoDestroy is TRUE and the domain already
1396 ended, then destroy() is called immediately."
1397
1398 if (.autoDestroy == autoDestroy) {
1399 return(.autoDestroy)
1400 }
1401
1402 oldValue <- .autoDestroy
1403 .autoDestroy <<- autoDestroy
1404
1405 if (autoDestroy) {
1406 if (!.destroyed && !is.null(.domain)) { # Make sure to not try to destroy twice.
1407 if (.domain$isEnded()) {
1408 destroy()
1409 } else {
1410 .autoDestroyHandle <<- onReactiveDomainEnded(.domain, .onDomainEnded)
1411 }
1412 }
1413 } else {
1414 if (!is.null(.autoDestroyHandle))
1415 .autoDestroyHandle()
1416 .autoDestroyHandle <<- NULL
1417 }
1418
1419 invisible(oldValue)
1420 },
1421 suspend = function() {
1422 "Causes this observer to stop scheduling flushes (re-executions) in
1423 response to invalidations. If the observer was invalidated prior to this
1424 call but it has not re-executed yet (because it waits until onFlush is
1425 called) then that re-execution will still occur, because the flush is
1426 already scheduled."
1427 .suspended <<- TRUE
1428 },
1429 resume = function() {
1430 "Causes this observer to start re-executing in response to invalidations.
1431 If the observer was invalidated while suspended, then it will schedule
1432 itself for re-execution (pending flush)."
1433 if (.suspended) {
1434 .suspended <<- FALSE
1435 .onResume()
1436 .onResume <<- function() NULL
1437 }
1438 invisible()
1439 },
1440 destroy = function() {
1441 "Prevents this observer from ever executing again (even if a flush has
1442 already been scheduled)."
1443
1444 # Make sure to not try to destory twice.
1445 if (.destroyed)
1446 return()
1447
1448 suspend()
1449 .destroyed <<- TRUE
1450
1451 if (!is.null(.autoDestroyHandle)) {
1452 .autoDestroyHandle()
1453 }
1454 .autoDestroyHandle <<- NULL
1455
1456 if (!is.null(.ctx)) {
1457 .ctx$invalidate()
1458 }
1459 },
1460 .onDomainEnded = function() {
1461 if (isTRUE(.autoDestroy)) {
1462 destroy()
1463 }
1464 }
1465 )
1466 )
1467
1468 #' Create a reactive observer
1469 #'
1470 #' Creates an observer from the given expression.
1471 #'
1472 #' An observer is like a reactive expression in that it can read reactive values
1473 #' and call reactive expressions, and will automatically re-execute when those
1474 #' dependencies change. But unlike reactive expressions, it doesn't yield a
1475 #' result and can't be used as an input to other reactive expressions. Thus,
1476 #' observers are only useful for their side effects (for example, performing
1477 #' I/O).
1478 #'
1479 #' Another contrast between reactive expressions and observers is their
1480 #' execution strategy. Reactive expressions use lazy evaluation; that is, when
1481 #' their dependencies change, they don't re-execute right away but rather wait
1482 #' until they are called by someone else. Indeed, if they are not called then
1483 #' they will never re-execute. In contrast, observers use eager evaluation; as
1484 #' soon as their dependencies change, they schedule themselves to re-execute.
1485 #'
1486 #' Starting with Shiny 0.10.0, observers are automatically destroyed by default
1487 #' when the [domain][domains] that owns them ends (e.g. when a Shiny
1488 #' session ends).
1489 #'
1490 #' @param x An expression (quoted or unquoted). Any return value will be
1491 #' ignored.
1492 #' @inheritParams reactive
1493 #' @param label A label for the observer, useful for debugging.
1494 #' @param suspended If `TRUE`, start the observer in a suspended state. If
1495 #' `FALSE` (the default), start in a non-suspended state.
1496 #' @param priority An integer or numeric that controls the priority with which
1497 #' this observer should be executed. A higher value means higher priority: an
1498 #' observer with a higher priority value will execute before all observers
1499 #' with lower priority values. Positive, negative, and zero values are
1500 #' allowed.
1501 #' @param domain See [domains].
1502 #' @param autoDestroy If `TRUE` (the default), the observer will be
1503 #' automatically destroyed when its domain (if any) ends.
1504 #' @param ..stacktraceon Advanced use only. For stack manipulation purposes; see
1505 #' [stacktrace()].
1506 #' @param ... Not used.
1507 #'
1508 #' @return An observer reference class object. This object has the following
1509 #' methods:
1510 #' \describe{
1511 #' \item{`suspend()`}{
1512 #' Causes this observer to stop scheduling flushes (re-executions) in
1513 #' response to invalidations. If the observer was invalidated prior to
1514 #' this call but it has not re-executed yet then that re-execution will
1515 #' still occur, because the flush is already scheduled.
1516 #' }
1517 #' \item{`resume()`}{
1518 #' Causes this observer to start re-executing in response to
1519 #' invalidations. If the observer was invalidated while suspended, then it
1520 #' will schedule itself for re-execution.
1521 #' }
1522 #' \item{`destroy()`}{
1523 #' Stops the observer from executing ever again, even if it is currently
1524 #' scheduled for re-execution.
1525 #' }
1526 #' \item{`setPriority(priority = 0)`}{
1527 #' Change this observer's priority. Note that if the observer is currently
1528 #' invalidated, then the change in priority will not take effect until the
1529 #' next invalidation--unless the observer is also currently suspended, in
1530 #' which case the priority change will be effective upon resume.
1531 #' }
1532 #' \item{`setAutoDestroy(autoDestroy)`}{
1533 #' Sets whether this observer should be automatically destroyed when its
1534 #' domain (if any) ends. If autoDestroy is TRUE and the domain already
1535 #' ended, then destroy() is called immediately."
1536 #' }
1537 #' \item{`onInvalidate(callback)`}{
1538 #' Register a callback function to run when this observer is invalidated.
1539 #' No arguments will be provided to the callback function when it is
1540 #' invoked.
1541 #' }
1542 #' }
1543 #'
1544 #' @examples
1545 #' values <- reactiveValues(A=1)
1546 #'
1547 #' obsB <- observe({
1548 #' print(values$A + 1)
1549 #' })
1550 #'
1551 #' # To store expressions for later conversion to observe, use rlang::quo()
1552 #' myquo <- rlang::quo({ print(values$A + 3) })
1553 #' obsC <- rlang::inject(observe(!!myquo))
1554 #'
1555 #' # (Legacy) Can use quoted expressions
1556 #' obsD <- observe(quote({ print(values$A + 2) }), quoted = TRUE)
1557 #'
1558 #' # In a normal Shiny app, the web client will trigger flush events. If you
1559 #' # are at the console, you can force a flush with flushReact()
1560 #' shiny:::flushReact()
1561 #' @export
1562 observe <- function(
1563 x,
1564 env = parent.frame(),
1565 quoted = FALSE,
1566 ...,
1567 label = NULL,
1568 suspended = FALSE,
1569 priority = 0,
1570 domain = getDefaultReactiveDomain(),
1571 autoDestroy = TRUE,
1572 ..stacktraceon = TRUE)
1573 {
1574 check_dots_empty()
1575
1576 func <- installExprFunction(x, "func", env, quoted)
1577
1578 call_srcref <- get_call_srcref()
1579 if (is.null(label)) {
1580 label <- rassignSrcrefToLabel(
1581 call_srcref,
1582 defaultLabel = funcToLabel(func, "observe", label)
1583 )
1584 }
1585
1586 o <- Observer$new(
1587 func,
1588 label = label,
1589 suspended = suspended,
1590 priority = priority,
1591 domain = domain,
1592 autoDestroy = autoDestroy,
1593 ..stacktraceon = ..stacktraceon
1594 )
1595 if (!is.null(call_srcref)) {
1596 o$.otelAttrs <- otel_srcref_attributes(call_srcref, fn_name = "observe")
1597 }
1598
1599 if (has_otel_collect("reactivity")) {
1600 o <- enable_otel_observe(o)
1601 }
1602
1603 invisible(o)
1604 }
1605
1606 #' Make a reactive variable
1607 #'
1608 #' Turns a normal variable into a reactive variable, that is, one that has
1609 #' reactive semantics when assigned or read in the usual ways. The variable may
1610 #' already exist; if so, its value will be used as the initial value of the
1611 #' reactive variable (or `NULL` if the variable did not exist).
1612 #'
1613 #' @param symbol Name of variable to make reactive, as a string.
1614 #' @param env Environment in which to create binding. Expert use only.
1615 #' @return None.
1616 #' @keywords internal
1617 #' @examples
1618 #' reactiveConsole(TRUE)
1619 #'
1620 #' a <- 10
1621 #' makeReactiveBinding("a")
1622 #'
1623 #' b <- reactive(a * -1)
1624 #' observe(print(b()))
1625 #'
1626 #' a <- 20
1627 #' a <- 30
1628 #'
1629 #' reactiveConsole(FALSE)
1630 #' @export
1631 makeReactiveBinding <- function(symbol, env = parent.frame()) {
1632 if (exists(symbol, envir = env, inherits = FALSE)) {
1633 initialValue <- env[[symbol]]
1634 rm(list = symbol, envir = env, inherits = FALSE)
1635 } else {
1636 initialValue <- NULL
1637 }
1638
1639 val <- reactiveVal(initialValue, label = symbol)
1640 makeActiveBinding(symbol, val, env = env)
1641
1642 invisible()
1643 }
1644
1645 # `%<-reactive%` <- function(name, value) {
1646 # sym <- deparse(substitute(name))
1647 # assign(sym, value, pos = parent.frame())
1648 # makeReactiveBinding(sym, env=parent.frame())
1649 # invisible(NULL)
1650 # }
1651
1652 # Causes flushReact to be called every time an expression is
1653 # entered into the top-level prompt
1654 setAutoflush <- local({
1655 callbackId <- NULL
1656
1657 function(enable) {
1658 if (xor(is.null(callbackId), isTRUE(enable))) {
1659 return(invisible())
1660 }
1661
1662 if (isTRUE(enable)) {
1663 callbackId <<- addTaskCallback(function(expr, value, ok, visible) {
1664 timerCallbacks$executeElapsed()
1665 flushReact()
1666 return(TRUE)
1667 })
1668 } else {
1669 removeTaskCallback(callbackId)
1670 callbackId <<- NULL
1671 }
1672 invisible()
1673 }
1674 })
1675
1676
1677 #' Activate reactivity in the console
1678 #'
1679 #' This is an experimental feature that allows you to enable reactivity
1680 #' at the console, for the purposes of experimentation and learning.
1681 #'
1682 #' @keywords internal
1683 #' @param enabled Turn console reactivity on or off?
1684 #' @export
1685 #' @examples
1686 #' reactiveConsole(TRUE)
1687 #' x <- reactiveVal(10)
1688 #' y <- observe({
1689 #' message("The value of x is ", x())
1690 #' })
1691 #' x(20)
1692 #' x(30)
1693 #' reactiveConsole(FALSE)
1694 reactiveConsole <- function(enabled) {
1695 options(shiny.suppressMissingContextError = enabled)
1696 setAutoflush(enabled)
1697 }
1698
1699 # ---------------------------------------------------------------------------
1700
1701 #' Timer
1702 #'
1703 #' Creates a reactive timer with the given interval. A reactive timer is like a
1704 #' reactive value, except reactive values are triggered when they are set, while
1705 #' reactive timers are triggered simply by the passage of time.
1706 #'
1707 #' [Reactive expressions][reactive] and observers that want to be
1708 #' invalidated by the timer need to call the timer function that
1709 #' `reactiveTimer` returns, even if the current time value is not actually
1710 #' needed.
1711 #'
1712 #' See [invalidateLater()] as a safer and simpler alternative.
1713 #'
1714 #' @param intervalMs How often to fire, in milliseconds
1715 #' @param session A session object. This is needed to cancel any scheduled
1716 #' invalidations after a user has ended the session. If `NULL`, then
1717 #' this invalidation will not be tied to any session, and so it will still
1718 #' occur.
1719 #' @return A no-parameter function that can be called from a reactive context,
1720 #' in order to cause that context to be invalidated the next time the timer
1721 #' interval elapses. Calling the returned function also happens to yield the
1722 #' current time (as in [base::Sys.time()]).
1723 #' @seealso [invalidateLater()]
1724 #'
1725 #' @examples
1726 #' ## Only run examples in interactive R sessions
1727 #' if (interactive()) {
1728 #'
1729 #' ui <- fluidPage(
1730 #' sliderInput("n", "Number of observations", 2, 1000, 500),
1731 #' plotOutput("plot")
1732 #' )
1733 #'
1734 #' server <- function(input, output) {
1735 #'
1736 #' # Anything that calls autoInvalidate will automatically invalidate
1737 #' # every 2 seconds.
1738 #' autoInvalidate <- reactiveTimer(2000)
1739 #'
1740 #' observe({
1741 #' # Invalidate and re-execute this reactive expression every time the
1742 #' # timer fires.
1743 #' autoInvalidate()
1744 #'
1745 #' # Do something each time this is invalidated.
1746 #' # The isolate() makes this observer _not_ get invalidated and re-executed
1747 #' # when input$n changes.
1748 #' print(paste("The value of input$n is", isolate(input$n)))
1749 #' })
1750 #'
1751 #' # Generate a new histogram each time the timer fires, but not when
1752 #' # input$n changes.
1753 #' output$plot <- renderPlot({
1754 #' autoInvalidate()
1755 #' hist(rnorm(isolate(input$n)))
1756 #' })
1757 #' }
1758 #'
1759 #' shinyApp(ui, server)
1760 #' }
1761 #' @export
1762 reactiveTimer <- function(intervalMs=1000, session = getDefaultReactiveDomain()) {
1763 # Need to make sure that session is resolved at creation, not when the
1764 # callback below is fired (see #1621).
1765 force(session)
1766
1767 # TODO-barret - ## leave alone for now
1768 # reactId <- nextGlobalReactId()
1769 # rLog$define(reactId, paste0("timer(", intervalMs, ")"))
1770
1771 scheduler <- defineScheduler(session)
1772
1773 dependents <- Map$new()
1774 timerHandle <- scheduler(intervalMs, function() {
1775 # Quit if the session is closed
1776 if (!is.null(session) && session$isClosed()) {
1777 return(invisible())
1778 }
1779
1780 timerHandle <<- scheduler(intervalMs, sys.function())
1781
1782 doInvalidate <- function() {
1783 lapply(
1784 dependents$values(),
1785 function(dep.ctx) {
1786 dep.ctx$invalidate()
1787 NULL
1788 })
1789 }
1790
1791 if (!is.null(session)) {
1792 # If this timer belongs to a session, we must wait until the next cycle is
1793 # ready to invalidate.
1794 session$cycleStartAction(doInvalidate)
1795 } else {
1796 # If this timer doesn't belong to a session, we invalidate right away.
1797 doInvalidate()
1798 }
1799 })
1800
1801 if (!is.null(session)) {
1802 session$onEnded(timerHandle)
1803 }
1804
1805 return(function() {
1806 newValue <- Sys.time()
1807 ctx <- getCurrentContext()
1808 if (!dependents$containsKey(ctx$id)) {
1809 dependents$set(ctx$id, ctx)
1810 ctx$onInvalidate(function() {
1811 dependents$remove(ctx$id)
1812 })
1813 }
1814 return(newValue)
1815 })
1816 }
1817
1818 #' Scheduled Invalidation
1819 #'
1820 #' Schedules the current reactive context to be invalidated in the given number
1821 #' of milliseconds.
1822 #'
1823 #' If this is placed within an observer or reactive expression, that object will
1824 #' be invalidated (and re-execute) after the interval has passed. The
1825 #' re-execution will reset the invalidation flag, so in a typical use case, the
1826 #' object will keep re-executing and waiting for the specified interval. It's
1827 #' possible to stop this cycle by adding conditional logic that prevents the
1828 #' `invalidateLater` from being run.
1829 #'
1830 #' @param millis Approximate milliseconds to wait before invalidating the
1831 #' current reactive context.
1832 #' @param session A session object. This is needed to cancel any scheduled
1833 #' invalidations after a user has ended the session. If `NULL`, then
1834 #' this invalidation will not be tied to any session, and so it will still
1835 #' occur.
1836 #'
1837 #' @seealso [reactiveTimer()] is a slightly less safe alternative.
1838 #'
1839 #' @examples
1840 #' ## Only run examples in interactive R sessions
1841 #' if (interactive()) {
1842 #'
1843 #' ui <- fluidPage(
1844 #' sliderInput("n", "Number of observations", 2, 1000, 500),
1845 #' plotOutput("plot")
1846 #' )
1847 #'
1848 #' server <- function(input, output, session) {
1849 #'
1850 #' observe({
1851 #' # Re-execute this reactive expression after 1000 milliseconds
1852 #' invalidateLater(1000, session)
1853 #'
1854 #' # Do something each time this is invalidated.
1855 #' # The isolate() makes this observer _not_ get invalidated and re-executed
1856 #' # when input$n changes.
1857 #' print(paste("The value of input$n is", isolate(input$n)))
1858 #' })
1859 #'
1860 #' # Generate a new histogram at timed intervals, but not when
1861 #' # input$n changes.
1862 #' output$plot <- renderPlot({
1863 #' # Re-execute this reactive expression after 2000 milliseconds
1864 #' invalidateLater(2000)
1865 #' hist(rnorm(isolate(input$n)))
1866 #' })
1867 #' }
1868 #'
1869 #' shinyApp(ui, server)
1870 #' }
1871 #' @export
1872 invalidateLater <- function(millis, session = getDefaultReactiveDomain()) {
1873 force(session)
1874
1875 ctx <- getCurrentContext()
1876 rLog$invalidateLater(ctx$.reactId, ctx$id, millis, session)
1877
1878 clear_on_ended_callback <- function() {}
1879
1880 scheduler <- defineScheduler(session)
1881
1882 timerHandle <- scheduler(millis, function() {
1883 if (is.null(session)) {
1884 ctx$invalidate()
1885 return(invisible())
1886 }
1887
1888 clear_on_ended_callback()
1889
1890 if (!session$isClosed()) {
1891 session$cycleStartAction(function() {
1892 ctx$invalidate()
1893 })
1894 }
1895
1896 invisible()
1897 })
1898
1899 if (!is.null(session)) {
1900 # timerHandle is a callback that clears the scheduled task. It gets
1901 # registered with session$onEnded() each time invalidateLater() is called.
1902 # So, to prevent these callbacks from building up and leaking memory, we
1903 # need to deregister the onEnded(timerHandle) callback each time when the
1904 # scheduled task executes; after the task executes, the timerHandle()
1905 # function is essentially a no-op, so we can deregister it.
1906 clear_on_ended_callback <- session$onEnded(timerHandle)
1907 }
1908
1909 invisible()
1910 }
1911
1912 coerceToFunc <- function(x) {
1913 force(x);
1914 if (is.function(x))
1915 return(x)
1916 else
1917 return(function() x)
1918 }
1919
1920 #' Reactive polling
1921 #'
1922 #' Used to create a reactive data source, which works by periodically polling a
1923 #' non-reactive data source.
1924 #'
1925 #' `reactivePoll` works by pairing a relatively cheap "check" function with
1926 #' a more expensive value retrieval function. The check function will be
1927 #' executed periodically and should always return a consistent value until the
1928 #' data changes. When the check function returns a different value, then the
1929 #' value retrieval function will be used to re-populate the data.
1930 #'
1931 #' Note that the check function doesn't return `TRUE` or `FALSE` to
1932 #' indicate whether the underlying data has changed. Rather, the check function
1933 #' indicates change by returning a different value from the previous time it was
1934 #' called.
1935 #'
1936 #' For example, `reactivePoll` is used to implement
1937 #' `reactiveFileReader` by pairing a check function that simply returns the
1938 #' last modified timestamp of a file, and a value retrieval function that
1939 #' actually reads the contents of the file.
1940 #'
1941 #' As another example, one might read a relational database table reactively by
1942 #' using a check function that does `SELECT MAX(timestamp) FROM table` and
1943 #' a value retrieval function that does `SELECT * FROM table`.
1944 #'
1945 #' The `intervalMillis`, `checkFunc`, and `valueFunc` functions
1946 #' will be executed in a reactive context; therefore, they may read reactive
1947 #' values and reactive expressions.
1948 #'
1949 #' @param intervalMillis Approximate number of milliseconds to wait between
1950 #' calls to `checkFunc`. This can be either a numeric value, or a
1951 #' function that returns a numeric value.
1952 #' @param session The user session to associate this file reader with, or
1953 #' `NULL` if none. If non-null, the reader will automatically stop when
1954 #' the session ends.
1955 #' @param checkFunc A relatively cheap function whose values over time will be
1956 #' tested for equality; inequality indicates that the underlying value has
1957 #' changed and needs to be invalidated and re-read using `valueFunc`. See
1958 #' Details.
1959 #' @param valueFunc A function that calculates the underlying value. See
1960 #' Details.
1961 #'
1962 #' @return A reactive expression that returns the result of `valueFunc`,
1963 #' and invalidates when `checkFunc` changes.
1964 #'
1965 #' @seealso [reactiveFileReader()]
1966 #'
1967 #' @examples
1968 #' function(input, output, session) {
1969 #'
1970 #' data <- reactivePoll(1000, session,
1971 #' # This function returns the time that log_file was last modified
1972 #' checkFunc = function() {
1973 #' if (file.exists(log_file))
1974 #' file.info(log_file)$mtime[1]
1975 #' else
1976 #' ""
1977 #' },
1978 #' # This function returns the content of log_file
1979 #' valueFunc = function() {
1980 #' read.csv(log_file)
1981 #' }
1982 #' )
1983 #'
1984 #' output$dataTable <- renderTable({
1985 #' data()
1986 #' })
1987 #' }
1988 #' @export
1989 reactivePoll <- function(intervalMillis, session, checkFunc, valueFunc) {
1990 reactive_poll_impl(
1991 fnName = "reactivePoll",
1992 intervalMillis = intervalMillis,
1993 session = session,
1994 checkFunc = checkFunc,
1995 valueFunc = valueFunc
1996 )
1997 }
1998
1999 reactive_poll_impl <- function(
2000 fnName,
2001 intervalMillis,
2002 session,
2003 checkFunc,
2004 valueFunc
2005 ) {
2006 intervalMillis <- coerceToFunc(intervalMillis)
2007
2008 fnName <- match.arg(fnName, c("reactivePoll", "reactiveFileReader"), several.ok = FALSE)
2009
2010 call_srcref <- get_call_srcref(-1)
2011 label <- rassignSrcrefToLabel(
2012 call_srcref,
2013 defaultLabel = "<anonymous>",
2014 fnName = fnName
2015 )
2016
2017 re_finalized <- FALSE
2018 env <- environment()
2019
2020 with_no_otel_collect({
2021 cookie <- reactiveVal(
2022 isolate(checkFunc()),
2023 label = sprintf("%s %s cookie", fnName, label)
2024 )
2025
2026 o <- observe({
2027 # When no one holds a reference to the reactive returned from
2028 # reactivePoll, destroy and remove the observer so that it doesn't keep
2029 # firing and hold onto resources.
2030 if (re_finalized) {
2031 o$destroy()
2032 rm(o, envir = env)
2033 return()
2034 }
2035
2036 cookie(checkFunc())
2037 invalidateLater(intervalMillis(), session)
2038 }, label = sprintf("%s %s cleanup", fnName, label))
2039 })
2040
2041 re <- reactive(label = sprintf("%s %s", fnName, label), {
2042 # Take a dependency on the cookie, so that when it changes, this
2043 # reactive expression is invalidated.
2044 cookie()
2045
2046 valueFunc()
2047 })
2048
2049 reg.finalizer(attr(re, "observable"), function(e) {
2050 re_finalized <<- TRUE
2051 })
2052
2053 # So that the observer and finalizer function don't (indirectly) hold onto a
2054 # reference to `re` and thus prevent it from getting GC'd.
2055 on.exit(rm(re))
2056
2057 local({
2058 impl <- attr(re, "observable", exact = TRUE)
2059 impl$.otelLabel <-
2060 if (fnName == "reactivePoll")
2061 otel_label_reactive_poll(label, domain = impl$.domain)
2062 else if (fnName == "reactiveFileReader")
2063 otel_label_reactive_file_reader(label, domain = impl$.domain)
2064 impl$.otelAttrs <- append_otel_srcref_attrs(impl$.otelAttrs, call_srcref, fn_name = fnName)
2065 })
2066
2067 return(re)
2068 }
2069
2070 #' Reactive file reader
2071 #'
2072 #' Given a file path and read function, returns a reactive data source for the
2073 #' contents of the file.
2074 #'
2075 #' `reactiveFileReader` works by periodically checking the file's last
2076 #' modified time; if it has changed, then the file is re-read and any reactive
2077 #' dependents are invalidated.
2078 #'
2079 #' The `intervalMillis`, `filePath`, and `readFunc` functions
2080 #' will each be executed in a reactive context; therefore, they may read
2081 #' reactive values and reactive expressions.
2082 #'
2083 #' @param intervalMillis Approximate number of milliseconds to wait between
2084 #' checks of the file's last modified time. This can be a numeric value, or a
2085 #' function that returns a numeric value.
2086 #' @param session The user session to associate this file reader with, or
2087 #' `NULL` if none. If non-null, the reader will automatically stop when
2088 #' the session ends.
2089 #' @param filePath The file path to poll against and to pass to `readFunc`.
2090 #' This can either be a single-element character vector, or a function that
2091 #' returns one.
2092 #' @param readFunc The function to use to read the file; must expect the first
2093 #' argument to be the file path to read. The return value of this function is
2094 #' used as the value of the reactive file reader.
2095 #' @param ... Any additional arguments to pass to `readFunc` whenever it is
2096 #' invoked.
2097 #'
2098 #' @return A reactive expression that returns the contents of the file, and
2099 #' automatically invalidates when the file changes on disk (as determined by
2100 #' last modified time).
2101 #'
2102 #' @seealso [reactivePoll()]
2103 #'
2104 #' @examples
2105 #' \dontrun{
2106 #' # Per-session reactive file reader
2107 #' function(input, output, session) {
2108 #' fileData <- reactiveFileReader(1000, session, 'data.csv', read.csv)
2109 #'
2110 #' output$data <- renderTable({
2111 #' fileData()
2112 #' })
2113 #' }
2114 #'
2115 #' # Cross-session reactive file reader. In this example, all sessions share
2116 #' # the same reader, so read.csv only gets executed once no matter how many
2117 #' # user sessions are connected.
2118 #' fileData <- reactiveFileReader(1000, NULL, 'data.csv', read.csv)
2119 #' function(input, output, session) {
2120 #' output$data <- renderTable({
2121 #' fileData()
2122 #' })
2123 #' }
2124 #' }
2125 #' @export
2126 reactiveFileReader <- function(intervalMillis, session, filePath, readFunc, ...) {
2127 filePath <- coerceToFunc(filePath)
2128 extraArgs <- list2(...)
2129
2130 reactive_poll_impl(
2131 fnName = "reactiveFileReader",
2132 intervalMillis = intervalMillis,
2133 session = session,
2134 checkFunc = function() {
2135 path <- filePath()
2136 info <- file.info(path)
2137 return(paste(path, info$mtime, info$size))
2138 },
2139 valueFunc = function() {
2140 do.call(readFunc, c(filePath(), extraArgs))
2141 }
2142 )
2143 }
2144
2145 #' Create a non-reactive scope for an expression
2146 #'
2147 #' Executes the given expression in a scope where reactive values or expression
2148 #' can be read, but they cannot cause the reactive scope of the caller to be
2149 #' re-evaluated when they change.
2150 #'
2151 #' Ordinarily, the simple act of reading a reactive value causes a relationship
2152 #' to be established between the caller and the reactive value, where a change
2153 #' to the reactive value will cause the caller to re-execute. (The same applies
2154 #' for the act of getting a reactive expression's value.) The `isolate`
2155 #' function lets you read a reactive value or expression without establishing this
2156 #' relationship.
2157 #'
2158 #' The expression given to `isolate()` is evaluated in the calling
2159 #' environment. This means that if you assign a variable inside the
2160 #' `isolate()`, its value will be visible outside of the `isolate()`.
2161 #' If you want to avoid this, you can use [base::local()] inside the
2162 #' `isolate()`.
2163 #'
2164 #' This function can also be useful for calling reactive expression at the
2165 #' console, which can be useful for debugging. To do so, simply wrap the
2166 #' calls to the reactive expression with `isolate()`.
2167 #'
2168 #' @param expr An expression that can access reactive values or expressions.
2169 #'
2170 #' @examples
2171 #' \dontrun{
2172 #' observe({
2173 #' input$saveButton # Do take a dependency on input$saveButton
2174 #'
2175 #' # isolate a simple expression
2176 #' data <- get(isolate(input$dataset)) # No dependency on input$dataset
2177 #' writeToDatabase(data)
2178 #' })
2179 #'
2180 #' observe({
2181 #' input$saveButton # Do take a dependency on input$saveButton
2182 #'
2183 #' # isolate a whole block
2184 #' data <- isolate({
2185 #' a <- input$valueA # No dependency on input$valueA or input$valueB
2186 #' b <- input$valueB
2187 #' c(a=a, b=b)
2188 #' })
2189 #' writeToDatabase(data)
2190 #' })
2191 #'
2192 #' observe({
2193 #' x <- 1
2194 #' # x outside of isolate() is affected
2195 #' isolate(x <- 2)
2196 #' print(x) # 2
2197 #'
2198 #' y <- 1
2199 #' # Use local() to avoid affecting calling environment
2200 #' isolate(local(y <- 2))
2201 #' print(y) # 1
2202 #' })
2203 #'
2204 #' }
2205 #'
2206 #' # Can also use isolate to call reactive expressions from the R console
2207 #' values <- reactiveValues(A=1)
2208 #' fun <- reactive({ as.character(values$A) })
2209 #' isolate(fun())
2210 #' # "1"
2211 #'
2212 #' # isolate also works if the reactive expression accesses values from the
2213 #' # input object, like input$x
2214 #' @export
2215 isolate <- function(expr) {
2216 if (hasCurrentContext()) {
2217 reactId <- getCurrentContext()$.reactId
2218 } else {
2219 reactId <- rLog$noReactId
2220 }
2221
2222 # Do not track otel spans for `isolate()`
2223 ctx <- Context$new(getDefaultReactiveDomain(), '[isolate]', type='isolate', reactId = reactId)
2224 on.exit(ctx$invalidate())
2225 # Matching ..stacktraceon../..stacktraceoff.. pair
2226 ..stacktraceoff..(ctx$run(function() {
2227 ..stacktraceon..(expr)
2228 }))
2229 }
2230
2231 #' Evaluate an expression without a reactive context
2232 #'
2233 #' Temporarily blocks the current reactive context and evaluates the given
2234 #' expression. Any attempt to directly access reactive values or expressions in
2235 #' `expr` will give the same results as doing it at the top-level (by
2236 #' default, an error).
2237 #'
2238 #' @param expr An expression to evaluate.
2239 #' @return The value of `expr`.
2240 #'
2241 #' @seealso [isolate()]
2242 #' @export
2243 maskReactiveContext <- function(expr) {
2244 .getReactiveEnvironment()$runWith(NULL, function() {
2245 expr
2246 })
2247 }
2248
2249 #' Event handler
2250 #'
2251 #' Respond to "event-like" reactive inputs, values, and expressions. As of Shiny
2252 #' 1.6.0, we recommend using [bindEvent()] instead of `eventReactive()` and
2253 #' `observeEvent()`. This is because `bindEvent()` can be composed with
2254 #' [bindCache()], and because it can also be used with `render` functions (like
2255 #' [renderText()] and [renderPlot()]).
2256 #'
2257 #' Shiny's reactive programming framework is primarily designed for calculated
2258 #' values (reactive expressions) and side-effect-causing actions (observers)
2259 #' that respond to *any* of their inputs changing. That's often what is
2260 #' desired in Shiny apps, but not always: sometimes you want to wait for a
2261 #' specific action to be taken from the user, like clicking an
2262 #' [actionButton()], before calculating an expression or taking an
2263 #' action. A reactive value or expression that is used to trigger other
2264 #' calculations in this way is called an *event*.
2265 #'
2266 #' These situations demand a more imperative, "event handling" style of
2267 #' programming that is possible--but not particularly intuitive--using the
2268 #' reactive programming primitives [observe()] and
2269 #' [isolate()]. `observeEvent` and `eventReactive` provide
2270 #' straightforward APIs for event handling that wrap `observe` and
2271 #' `isolate`.
2272 #'
2273 #' Use `observeEvent` whenever you want to *perform an action* in
2274 #' response to an event. (Note that "recalculate a value" does not generally
2275 #' count as performing an action--see `eventReactive` for that.) The first
2276 #' argument is the event you want to respond to, and the second argument is a
2277 #' function that should be called whenever the event occurs. Note that
2278 #' `observeEvent()` is equivalent to using `observe() %>% bindEvent()` and as of
2279 #' Shiny 1.6.0, we recommend the latter.
2280 #'
2281 #' Use `eventReactive` to create a *calculated value* that only
2282 #' updates in response to an event. This is just like a normal
2283 #' [reactive expression][reactive] except it ignores all the usual
2284 #' invalidations that come from its reactive dependencies; it only invalidates
2285 #' in response to the given event. Note that
2286 #' `eventReactive()` is equivalent to using `reactive() %>% bindEvent()` and as of
2287 #' Shiny 1.6.0, we recommend the latter.
2288 #'
2289 #' @section ignoreNULL and ignoreInit:
2290 #'
2291 #' Both `observeEvent` and `eventReactive` take an `ignoreNULL`
2292 #' parameter that affects behavior when the `eventExpr` evaluates to
2293 #' `NULL` (or in the special case of an [actionButton()],
2294 #' `0`). In these cases, if `ignoreNULL` is `TRUE`, then an
2295 #' `observeEvent` will not execute and an `eventReactive` will raise a
2296 #' silent [validation][validate] error. This is useful behavior if you
2297 #' don't want to do the action or calculation when your app first starts, but
2298 #' wait for the user to initiate the action first (like a "Submit" button);
2299 #' whereas `ignoreNULL=FALSE` is desirable if you want to initially perform
2300 #' the action/calculation and just let the user re-initiate it (like a
2301 #' "Recalculate" button).
2302 #'
2303 #' Likewise, both `observeEvent` and `eventReactive` also take in an
2304 #' `ignoreInit` argument. By default, both of these will run right when they
2305 #' are created (except if, at that moment, `eventExpr` evaluates to `NULL`
2306 #' and `ignoreNULL` is `TRUE`). But when responding to a click of an action
2307 #' button, it may often be useful to set `ignoreInit` to `TRUE`. For
2308 #' example, if you're setting up an `observeEvent` for a dynamically created
2309 #' button, then `ignoreInit = TRUE` will guarantee that the action (in
2310 #' `handlerExpr`) will only be triggered when the button is actually clicked,
2311 #' instead of also being triggered when it is created/initialized. Similarly,
2312 #' if you're setting up an `eventReactive` that responds to a dynamically
2313 #' created button used to refresh some data (then returned by that `eventReactive`),
2314 #' then you should use `eventReactive([...], ignoreInit = TRUE)` if you want
2315 #' to let the user decide if/when they want to refresh the data (since, depending
2316 #' on the app, this may be a computationally expensive operation).
2317 #'
2318 #' Even though `ignoreNULL` and `ignoreInit` can be used for similar
2319 #' purposes they are independent from one another. Here's the result of combining
2320 #' these:
2321
2322 #'
2323 #' \describe{
2324 #' \item{`ignoreNULL = TRUE` and `ignoreInit = FALSE`}{
2325 #' This is the default. This combination means that `handlerExpr`/
2326 #' `valueExpr` will run every time that `eventExpr` is not
2327 #' `NULL`. If, at the time of the creation of the
2328 #' `observeEvent`/`eventReactive`, `eventExpr` happens
2329 #' to *not* be `NULL`, then the code runs.
2330 #' }
2331 #' \item{`ignoreNULL = FALSE` and `ignoreInit = FALSE`}{
2332 #' This combination means that `handlerExpr`/`valueExpr` will
2333 #' run every time no matter what.
2334 #' }
2335 #' \item{`ignoreNULL = FALSE` and `ignoreInit = TRUE`}{
2336 #' This combination means that `handlerExpr`/`valueExpr` will
2337 #' *not* run when the `observeEvent`/`eventReactive` is
2338 #' created (because `ignoreInit = TRUE`), but it will run every
2339 #' other time.
2340 #' }
2341 #' \item{`ignoreNULL = TRUE` and `ignoreInit = TRUE`}{
2342 #' This combination means that `handlerExpr`/`valueExpr` will
2343 #' *not* run when the `observeEvent`/`eventReactive` is
2344 #' created (because `ignoreInit = TRUE`). After that,
2345 #' `handlerExpr`/`valueExpr` will run every time that
2346 #' `eventExpr` is not `NULL`.
2347 #' }
2348 #' }
2349 #'
2350 #' @param eventExpr A (quoted or unquoted) expression that represents the event;
2351 #' this can be a simple reactive value like `input$click`, a call to a
2352 #' reactive expression like `dataset()`, or even a complex expression
2353 #' inside curly braces
2354 #' @param handlerExpr The expression to call whenever `eventExpr` is
2355 #' invalidated. This should be a side-effect-producing action (the return
2356 #' value will be ignored). It will be executed within an [isolate()]
2357 #' scope.
2358 #' @param valueExpr The expression that produces the return value of the
2359 #' `eventReactive`. It will be executed within an [isolate()]
2360 #' scope.
2361 #' @param event.env The parent environment for the reactive expression. By default,
2362 #' this is the calling environment, the same as when defining an ordinary
2363 #' non-reactive expression. If `eventExpr` is a quosure and `event.quoted` is `TRUE`,
2364 #' then `event.env` is ignored.
2365 #' @param event.quoted If it is `TRUE`, then the [`quote()`]ed value of `eventExpr`
2366 #' will be used when `eventExpr` is evaluated. If `eventExpr` is a quosure and you
2367 #' would like to use its expression as a value for `eventExpr`, then you must set
2368 #' `event.quoted` to `TRUE`.
2369 #' @param handler.env The parent environment for the reactive expression. By default,
2370 #' this is the calling environment, the same as when defining an ordinary
2371 #' non-reactive expression. If `handlerExpr` is a quosure and `handler.quoted` is `TRUE`,
2372 #' then `handler.env` is ignored.
2373 #' @param handler.quoted If it is `TRUE`, then the [`quote()`]ed value of `handlerExpr`
2374 #' will be used when `handlerExpr` is evaluated. If `handlerExpr` is a quosure and you
2375 #' would like to use its expression as a value for `handlerExpr`, then you must set
2376 #' `handler.quoted` to `TRUE`.
2377 #' @param value.env The parent environment for the reactive expression. By default,
2378 #' this is the calling environment, the same as when defining an ordinary
2379 #' non-reactive expression. If `valueExpr` is a quosure and `value.quoted` is `TRUE`,
2380 #' then `value.env` is ignored.
2381 #' @param value.quoted If it is `TRUE`, then the [`quote()`]ed value of `valueExpr`
2382 #' will be used when `valueExpr` is evaluated. If `valueExpr` is a quosure and you
2383 #' would like to use its expression as a value for `valueExpr`, then you must set
2384 #' `value.quoted` to `TRUE`.
2385 #' @param label A label for the observer or reactive, useful for debugging.
2386 #' @param suspended If `TRUE`, start the observer in a suspended state. If
2387 #' `FALSE` (the default), start in a non-suspended state.
2388 #' @param priority An integer or numeric that controls the priority with which
2389 #' this observer should be executed. An observer with a given priority level
2390 #' will always execute sooner than all observers with a lower priority level.
2391 #' Positive, negative, and zero values are allowed.
2392 #' @param domain See [domains].
2393 #' @param autoDestroy If `TRUE` (the default), the observer will be
2394 #' automatically destroyed when its domain (if any) ends.
2395 #' @param ignoreNULL Whether the action should be triggered (or value
2396 #' calculated, in the case of `eventReactive`) when the input event expression
2397 #' is `NULL`. See Details.
2398 #' @param ignoreInit If `TRUE`, then, when this `observeEvent` is
2399 #' first created/initialized, ignore the `handlerExpr` (the second
2400 #' argument), whether it is otherwise supposed to run or not. The default is
2401 #' `FALSE`. See Details.
2402 #' @param once Whether this `observeEvent` should be immediately destroyed
2403 #' after the first time that the code in `handlerExpr` is run. This
2404 #' pattern is useful when you want to subscribe to a event that should only
2405 #' happen once.
2406 #' @param ... Currently not used.
2407 #'
2408 #' @return `observeEvent` returns an observer reference class object (see
2409 #' [observe()]). `eventReactive` returns a reactive expression
2410 #' object (see [reactive()]).
2411 #'
2412 #' @seealso [actionButton()]
2413 #'
2414 #' @examples
2415 #' ## Only run examples in interactive R sessions
2416 #' if (interactive()) {
2417 #'
2418 #' ## App 1: Sample usage
2419 #' shinyApp(
2420 #' ui = fluidPage(
2421 #' column(4,
2422 #' numericInput("x", "Value", 5),
2423 #' br(),
2424 #' actionButton("button", "Show")
2425 #' ),
2426 #' column(8, tableOutput("table"))
2427 #' ),
2428 #' server = function(input, output) {
2429 #' # Take an action every time button is pressed;
2430 #' # here, we just print a message to the console
2431 #' observeEvent(input$button, {
2432 #' cat("Showing", input$x, "rows\n")
2433 #' })
2434 #' # The observeEvent() above is equivalent to:
2435 #' # observe({
2436 #' # cat("Showing", input$x, "rows\n")
2437 #' # }) %>%
2438 #' # bindEvent(input$button)
2439 #'
2440 #' # Take a reactive dependency on input$button, but
2441 #' # not on any of the stuff inside the function
2442 #' df <- eventReactive(input$button, {
2443 #' head(cars, input$x)
2444 #' })
2445 #' output$table <- renderTable({
2446 #' df()
2447 #' })
2448 #' }
2449 #' )
2450 #'
2451 #' ## App 2: Using `once`
2452 #' shinyApp(
2453 #' ui = basicPage( actionButton("go", "Go")),
2454 #' server = function(input, output, session) {
2455 #' observeEvent(input$go, {
2456 #' print(paste("This will only be printed once; all",
2457 #' "subsequent button clicks won't do anything"))
2458 #' }, once = TRUE)
2459 #' # The observeEvent() above is equivalent to:
2460 #' # observe({
2461 #' # print(paste("This will only be printed once; all",
2462 #' # "subsequent button clicks won't do anything"))
2463 #' # }) %>%
2464 #' # bindEvent(input$go, once = TRUE)
2465 #' }
2466 #' )
2467 #'
2468 #' ## App 3: Using `ignoreInit` and `once`
2469 #' shinyApp(
2470 #' ui = basicPage(actionButton("go", "Go")),
2471 #' server = function(input, output, session) {
2472 #' observeEvent(input$go, {
2473 #' insertUI("#go", "afterEnd",
2474 #' actionButton("dynamic", "click to remove"))
2475 #'
2476 #' # set up an observer that depends on the dynamic
2477 #' # input, so that it doesn't run when the input is
2478 #' # created, and only runs once after that (since
2479 #' # the side effect is remove the input from the DOM)
2480 #' observeEvent(input$dynamic, {
2481 #' removeUI("#dynamic")
2482 #' }, ignoreInit = TRUE, once = TRUE)
2483 #' })
2484 #' }
2485 #' )
2486 #' }
2487 #' @export
2488 observeEvent <- function(eventExpr, handlerExpr,
2489 event.env = parent.frame(), event.quoted = FALSE,
2490 handler.env = parent.frame(), handler.quoted = FALSE,
2491 ...,
2492 label = NULL, suspended = FALSE, priority = 0,
2493 domain = getDefaultReactiveDomain(), autoDestroy = TRUE,
2494 ignoreNULL = TRUE, ignoreInit = FALSE, once = FALSE)
2495 {
2496 check_dots_empty()
2497
2498 eventQ <- exprToQuo(eventExpr, event.env, event.quoted)
2499 handlerQ <- exprToQuo(handlerExpr, handler.env, handler.quoted)
2500
2501 call_srcref <- get_call_srcref()
2502 if (is.null(label)) {
2503 label <- rassignSrcrefToLabel(
2504 call_srcref,
2505 defaultLabel = quoToLabel(eventQ, "observeEvent", label)
2506 )
2507 }
2508
2509 with_no_otel_collect({
2510 handler <- inject(observe(
2511 !!handlerQ,
2512 label = label,
2513 suspended = suspended,
2514 priority = priority,
2515 domain = domain,
2516 autoDestroy = TRUE,
2517 ..stacktraceon = TRUE
2518 ))
2519
2520 o <- inject(bindEvent(
2521 ignoreNULL = ignoreNULL,
2522 ignoreInit = ignoreInit,
2523 once = once,
2524 label = label,
2525 !!eventQ,
2526 x = handler
2527 ))
2528 })
2529
2530 if (!is.null(call_srcref)) {
2531 o$.otelAttrs <- otel_srcref_attributes(call_srcref, fn_name = "observeEvent")
2532 }
2533 if (has_otel_collect("reactivity")) {
2534 o <- enable_otel_observe(o)
2535 }
2536
2537 invisible(o)
2538 }
2539
2540 #' @rdname observeEvent
2541 #' @export
2542 eventReactive <- function(eventExpr, valueExpr,
2543 event.env = parent.frame(), event.quoted = FALSE,
2544 value.env = parent.frame(), value.quoted = FALSE,
2545 ...,
2546 label = NULL, domain = getDefaultReactiveDomain(),
2547 ignoreNULL = TRUE, ignoreInit = FALSE)
2548 {
2549 check_dots_empty()
2550
2551 eventQ <- exprToQuo(eventExpr, event.env, event.quoted)
2552 valueQ <- exprToQuo(valueExpr, value.env, value.quoted)
2553
2554 func <- installExprFunction(eventExpr, "func", event.env, event.quoted, wrappedWithLabel = FALSE)
2555 # Attach a label and a reference to the original user source for debugging
2556 userEventExpr <- fn_body(func)
2557
2558 call_srcref <- get_call_srcref()
2559 if (is.null(label)) {
2560 label <- rassignSrcrefToLabel(
2561 call_srcref,
2562 defaultLabel = exprToLabel(userEventExpr, "eventReactive", label)
2563 )
2564 }
2565
2566 with_no_otel_collect({
2567 value_r <- inject(reactive(!!valueQ, domain = domain, label = label))
2568
2569 r <- inject(bindEvent(
2570 ignoreNULL = ignoreNULL,
2571 ignoreInit = ignoreInit,
2572 label = label,
2573 !!eventQ,
2574 x = value_r
2575 ))
2576 })
2577
2578 if (!is.null(call_srcref)) {
2579 impl <- attr(r, "observable", exact = TRUE)
2580 impl$.otelAttrs <- otel_srcref_attributes(call_srcref, fn_name = "eventReactive")
2581 }
2582 if (has_otel_collect("reactivity")) {
2583 r <- enable_otel_reactive_expr(r)
2584 }
2585
2586
2587 return(r)
2588 }
2589
2590 isNullEvent <- function(value) {
2591 is.null(value) || (inherits(value, 'shinyActionButtonValue') && value == 0)
2592 }
2593
2594 #' Slow down a reactive expression with debounce/throttle
2595 #'
2596 #' Transforms a reactive expression by preventing its invalidation signals from
2597 #' being sent unnecessarily often. This lets you ignore a very "chatty" reactive
2598 #' expression until it becomes idle, which is useful when the intermediate
2599 #' values don't matter as much as the final value, and the downstream
2600 #' calculations that depend on the reactive expression take a long time.
2601 #' `debounce` and `throttle` use different algorithms for slowing down
2602 #' invalidation signals; see Details.
2603 #'
2604 #' @section Limitations:
2605 #'
2606 #' Because R is single threaded, we can't come close to guaranteeing that the
2607 #' timing of debounce/throttle (or any other timing-related functions in
2608 #' Shiny) will be consistent or accurate; at the time we want to emit an
2609 #' invalidation signal, R may be performing a different task and we have no
2610 #' way to interrupt it (nor would we necessarily want to if we could).
2611 #' Therefore, it's best to think of the time windows you pass to these
2612 #' functions as minimums.
2613 #'
2614 #' You may also see undesirable behavior if the amount of time spent doing
2615 #' downstream processing for each change approaches or exceeds the time
2616 #' window: in this case, debounce/throttle may not have any effect, as the
2617 #' time each subsequent event is considered is already after the time window
2618 #' has expired.
2619 #'
2620 #' @details
2621 #'
2622 #' This is not a true debounce/throttle in that it will not prevent `r`
2623 #' from being called many times (in fact it may be called more times than
2624 #' usual), but rather, the reactive invalidation signal that is produced by
2625 #' `r` is debounced/throttled instead. Therefore, these functions should be
2626 #' used when `r` is cheap but the things it will trigger (downstream
2627 #' outputs and reactives) are expensive.
2628 #'
2629 #' Debouncing means that every invalidation from `r` will be held for the
2630 #' specified time window. If `r` invalidates again within that time window,
2631 #' then the timer starts over again. This means that as long as invalidations
2632 #' continually arrive from `r` within the time window, the debounced
2633 #' reactive will not invalidate at all. Only after the invalidations stop (or
2634 #' slow down sufficiently) will the downstream invalidation be sent.
2635 #'
2636 #' `ooo-oo-oo---- => -----------o-`
2637 #'
2638 #' (In this graphical depiction, each character represents a unit of time, and
2639 #' the time window is 3 characters.)
2640 #'
2641 #' Throttling, on the other hand, delays invalidation if the *throttled*
2642 #' reactive recently (within the time window) invalidated. New `r`
2643 #' invalidations do not reset the time window. This means that if invalidations
2644 #' continually come from `r` within the time window, the throttled reactive
2645 #' will invalidate regularly, at a rate equal to or slower than the time
2646 #' window.
2647 #'
2648 #' `ooo-oo-oo---- => o--o--o--o---`
2649 #'
2650 #' @param r A reactive expression (that invalidates too often).
2651 #' @param millis The debounce/throttle time window. You may optionally pass a
2652 #' no-arg function or reactive expression instead, e.g. to let the end-user
2653 #' control the time window.
2654 #' @param priority Debounce/throttle is implemented under the hood using
2655 #' [observers][observe]. Use this parameter to set the priority of
2656 #' these observers. Generally, this should be higher than the priorities of
2657 #' downstream observers and outputs (which default to zero).
2658 #' @param domain See [domains].
2659 #'
2660 #' @examples
2661 #' ## Only run examples in interactive R sessions
2662 #' if (interactive()) {
2663 #' options(device.ask.default = FALSE)
2664 #'
2665 #' library(shiny)
2666 #' library(magrittr)
2667 #'
2668 #' ui <- fluidPage(
2669 #' plotOutput("plot", click = clickOpts("hover")),
2670 #' helpText("Quickly click on the plot above, while watching the result table below:"),
2671 #' tableOutput("result")
2672 #' )
2673 #'
2674 #' server <- function(input, output, session) {
2675 #' hover <- reactive({
2676 #' if (is.null(input$hover))
2677 #' list(x = NA, y = NA)
2678 #' else
2679 #' input$hover
2680 #' })
2681 #' hover_d <- hover %>% debounce(1000)
2682 #' hover_t <- hover %>% throttle(1000)
2683 #'
2684 #' output$plot <- renderPlot({
2685 #' plot(cars)
2686 #' })
2687 #'
2688 #' output$result <- renderTable({
2689 #' data.frame(
2690 #' mode = c("raw", "throttle", "debounce"),
2691 #' x = c(hover()$x, hover_t()$x, hover_d()$x),
2692 #' y = c(hover()$y, hover_t()$y, hover_d()$y)
2693 #' )
2694 #' })
2695 #' }
2696 #'
2697 #' shinyApp(ui, server)
2698 #' }
2699 #'
2700 #' @export
2701 debounce <- function(r, millis, priority = 100, domain = getDefaultReactiveDomain()) {
2702 # Do not bind OpenTelemetry spans for debounce reactivity internals,
2703 # except for the eventReactive that is returned.
2704
2705 force(r)
2706 force(millis)
2707
2708 call_srcref <- get_call_srcref()
2709 label <- rassignSrcrefToLabel(
2710 call_srcref,
2711 defaultLabel = "<anonymous>"
2712 )
2713
2714 if (!is.function(millis)) {
2715 origMillis <- millis
2716 millis <- function() origMillis
2717 }
2718
2719 with_no_otel_collect({
2720 trigger <- reactiveVal(NULL, label = sprintf("debounce %s trigger", label))
2721 # the deadline for the timer to fire; NULL if not scheduled
2722 when <- reactiveVal(NULL, label = sprintf("debounce %s when", label))
2723
2724 # Responsible for tracking when r() changes.
2725 firstRun <- TRUE
2726 observe(
2727 label = sprintf("debounce %s tracker", label),
2728 domain = domain,
2729 priority = priority,
2730 {
2731 if (firstRun) {
2732 # During the first run we don't want to set `when`, as this will kick
2733 # off the timer. We only want to do that when we see `r()` change.
2734 firstRun <<- FALSE
2735
2736 # Ensure r() is called only after setting firstRun to FALSE since r()
2737 # may throw an error
2738 try(r(), silent = TRUE)
2739 return()
2740 }
2741 # This ensures r() is still tracked after firstRun
2742 try(r(), silent = TRUE)
2743
2744 # The value (or possibly millis) changed. Start or reset the timer.
2745 when(
2746 getDomainTimeMs(domain) + millis()
2747 )
2748 }
2749 )
2750
2751 # This observer is the timer. It rests until `when` elapses, then touches
2752 # `trigger`.
2753 observe(
2754 label = sprintf("debounce %s timer", label),
2755 domain = domain,
2756 priority = priority,
2757 {
2758 if (is.null(when()))
2759 return()
2760
2761 now <- getDomainTimeMs(domain)
2762 if (now >= when()) {
2763 # Mod by 999999999 to get predictable overflow behavior
2764 trigger(
2765 isolate(trigger() %||% 0) %% 999999999 + 1
2766 )
2767 when(NULL)
2768 } else {
2769 invalidateLater(when() - now)
2770 }
2771 }
2772 )
2773
2774 })
2775
2776 # This is the actual reactive that is returned to the user. It returns the
2777 # value of r(), but only invalidates/updates when `trigger` is touched.
2778 er <- eventReactive(
2779 {trigger()}, {r()},
2780 label = sprintf("debounce %s result", label), ignoreNULL = FALSE, domain = domain
2781 )
2782
2783 # Update the otel label
2784 local({
2785 er_impl <- attr(er, "observable", exact = TRUE)
2786 er_impl$.otelLabel <- otel_label_debounce(label, domain = domain)
2787 er_impl$.otelAttrs <- append_otel_srcref_attrs(er_impl$.otelAttrs, call_srcref, fn_name = "debounce")
2788 })
2789
2790 with_no_otel_collect({
2791 # Force the value of er to be immediately cached upon creation. It's very hard
2792 # to explain why this observer is needed, but if you want to understand, try
2793 # commenting it out and studying the unit test failure that results.
2794 primer <- observe({
2795 primer$destroy()
2796 try(er(), silent = TRUE)
2797 }, label = sprintf("debounce %s primer", label), domain = domain, priority = priority)
2798 })
2799
2800 er
2801 }
2802
2803 #' @rdname debounce
2804 #' @export
2805 throttle <- function(r, millis, priority = 100, domain = getDefaultReactiveDomain()) {
2806 # Do not bind OpenTelemetry spans for throttle reactivity internals,
2807 # except for the eventReactive that is returned.
2808
2809 force(r)
2810 force(millis)
2811
2812 call_srcref <- get_call_srcref()
2813 label <- rassignSrcrefToLabel(
2814 call_srcref,
2815 defaultLabel = "<anonymous>"
2816 )
2817
2818 if (!is.function(millis)) {
2819 origMillis <- millis
2820 millis <- function() origMillis
2821 }
2822
2823 with_no_otel_collect({
2824 trigger <- reactiveVal(0, label = sprintf("throttle %s trigger", label))
2825 # Last time we fired; NULL if never
2826 lastTriggeredAt <- reactiveVal(NULL, label = sprintf("throttle %s last triggered at", label))
2827 # If TRUE, trigger again when timer elapses
2828 pending <- reactiveVal(FALSE, label = sprintf("throttle %s pending", label))
2829 })
2830
2831 blackoutMillisLeft <- function() {
2832 if (is.null(lastTriggeredAt())) {
2833 0
2834 } else {
2835 max(0, lastTriggeredAt() + millis() - getDomainTimeMs(domain))
2836 }
2837 }
2838
2839 update_trigger <- function() {
2840 lastTriggeredAt(getDomainTimeMs(domain))
2841 # Mod by 999999999 to get predictable overflow behavior
2842 trigger(isolate(trigger()) %% 999999999 + 1)
2843 pending(FALSE)
2844 }
2845
2846 with_no_otel_collect({
2847 # Responsible for tracking when f() changes.
2848 observeEvent(try(r(), silent = TRUE), {
2849 if (pending()) {
2850 # In a blackout period and someone already scheduled; do nothing
2851 } else if (blackoutMillisLeft() > 0) {
2852 # In a blackout period but this is the first change in that period; set
2853 # pending so that a trigger will be scheduled at the end of the period
2854 pending(TRUE)
2855 } else {
2856 # Not in a blackout period. Trigger, which will start a new blackout
2857 # period.
2858 update_trigger()
2859 }
2860 }, label = sprintf("throttle %s tracker", label), ignoreNULL = FALSE, priority = priority, domain = domain)
2861
2862 observe({
2863 if (!pending()) {
2864 return()
2865 }
2866
2867 timeout <- blackoutMillisLeft()
2868 if (timeout > 0) {
2869 invalidateLater(timeout)
2870 } else {
2871 update_trigger()
2872 }
2873 }, label = sprintf("throttle %s trigger", label), priority = priority, domain = domain)
2874 })
2875
2876 # This is the actual reactive that is returned to the user. It returns the
2877 # value of r(), but only invalidates/updates when trigger is touched.
2878 er <- eventReactive({trigger()}, {
2879 r()
2880 }, label = sprintf("throttle %s result", label), ignoreNULL = FALSE, domain = domain)
2881
2882 # Update the otel label
2883 local({
2884 er_impl <- attr(er, "observable", exact = TRUE)
2885 er_impl$.otelLabel <- otel_label_throttle(label, domain = domain)
2886 er_impl$.otelAttrs <- append_otel_srcref_attrs(er_impl$.otelAttrs, call_srcref, fn_name = "throttle")
2887 })
2888
2889 er
2890 }