Debian Codegraph @

R/bind-event.R

raw
1 #' Make an object respond only to specified reactive events
2 #'
3 #' @description
4 #'
5 #' Modify an object to respond to "event-like" reactive inputs, values, and
6 #' expressions. `bindEvent()` can be used with reactive expressions, render
7 #' functions, and observers. The resulting object takes a reactive dependency on
8 #' the `...` arguments, and not on the original object's code. This can, for
9 #' example, be used to make an observer execute only when a button is pressed.
10 #'
11 #' `bindEvent()` was added in Shiny 1.6.0. When it is used with [reactive()] and
12 #' [observe()], it does the same thing as [eventReactive()] and
13 #' [observeEvent()]. However, `bindEvent()` is more flexible: it can be combined
14 #' with [bindCache()], and it can also be used with `render` functions (like
15 #' [renderText()] and [renderPlot()]).
16 #'
17 #' @section Details:
18 #'
19 #' Shiny's reactive programming framework is primarily designed for calculated
20 #' values (reactive expressions) and side-effect-causing actions (observers)
21 #' that respond to *any* of their inputs changing. That's often what is
22 #' desired in Shiny apps, but not always: sometimes you want to wait for a
23 #' specific action to be taken from the user, like clicking an
24 #' [actionButton()], before calculating an expression or taking an action. A
25 #' reactive value or expression that is used to trigger other calculations in
26 #' this way is called an *event*.
27 #'
28 #' These situations demand a more imperative, "event handling" style of
29 #' programming that is possible--but not particularly intuitive--using the
30 #' reactive programming primitives [observe()] and [isolate()]. `bindEvent()`
31 #' provides a straightforward API for event handling that wraps `observe` and
32 #' `isolate`.
33 #'
34 #' The `...` arguments are captured as expressions and combined into an
35 #' **event expression**. When this event expression is invalidated (when its
36 #' upstream reactive inputs change), that is an **event**, and it will cause
37 #' the original object's code to execute.
38 #'
39 #' Use `bindEvent()` with `observe()` whenever you want to *perform an action*
40 #' in response to an event. (This does the same thing as [observeEvent()],
41 #' which was available in Shiny prior to version 1.6.0.) Note that
42 #' "recalculate a value" does not generally count as performing an action --
43 #' use [reactive()] for that.
44 #'
45 #' Use `bindEvent()` with `reactive()` to create a *calculated value* that
46 #' only updates in response to an event. This is just like a normal [reactive
47 #' expression][reactive] except it ignores all the usual invalidations that
48 #' come from its reactive dependencies; it only invalidates in response to the
49 #' given event. (This does the same thing as [eventReactive()], which was
50 #' available in Shiny prior to version 1.6.0.)
51 #'
52 #' `bindEvent()` is often used with [bindCache()].
53 #'
54 #' @section ignoreNULL and ignoreInit:
55 #'
56 #' `bindEvent()` takes an `ignoreNULL` parameter that affects behavior when
57 #' the event expression evaluates to `NULL` (or in the special case of an
58 #' [actionButton()], `0`). In these cases, if `ignoreNULL` is `TRUE`, then it
59 #' will raise a silent [validation][validate] error. This is useful behavior
60 #' if you don't want to do the action or calculation when your app first
61 #' starts, but wait for the user to initiate the action first (like a "Submit"
62 #' button); whereas `ignoreNULL=FALSE` is desirable if you want to initially
63 #' perform the action/calculation and just let the user re-initiate it (like a
64 #' "Recalculate" button).
65 #'
66 #' `bindEvent()` also takes an `ignoreInit` argument. By default, reactive
67 #' expressions and observers will run on the first reactive flush after they
68 #' are created (except if, at that moment, the event expression evaluates to
69 #' `NULL` and `ignoreNULL` is `TRUE`). But when responding to a click of an
70 #' action button, it may often be useful to set `ignoreInit` to `TRUE`. For
71 #' example, if you're setting up an observer to respond to a dynamically
72 #' created button, then `ignoreInit = TRUE` will guarantee that the action
73 #' will only be triggered when the button is actually clicked, instead of also
74 #' being triggered when it is created/initialized. Similarly, if you're
75 #' setting up a reactive that responds to a dynamically created button used to
76 #' refresh some data (which is then returned by that `reactive`), then you
77 #' should use `reactive(...) %>% bindEvent(..., ignoreInit = TRUE)` if you
78 #' want to let the user decide if/when they want to refresh the data (since,
79 #' depending on the app, this may be a computationally expensive operation).
80 #'
81 #' Even though `ignoreNULL` and `ignoreInit` can be used for similar purposes
82 #' they are independent from one another. Here's the result of combining
83 #' these:
84
85 #'
86 #' \describe{
87 #' \item{`ignoreNULL = TRUE` and `ignoreInit = FALSE`}{
88 #' This is the default. This combination means that reactive/observer code
89 #' will run every time that event expression is not
90 #' `NULL`. If, at the time of creation, the event expression happens
91 #' to *not* be `NULL`, then the code runs.
92 #' }
93 #' \item{`ignoreNULL = FALSE` and `ignoreInit = FALSE`}{
94 #' This combination means that reactive/observer code will
95 #' run every time no matter what.
96 #' }
97 #' \item{`ignoreNULL = FALSE` and `ignoreInit = TRUE`}{
98 #' This combination means that reactive/observer code will
99 #' *not* run at the time of creation (because `ignoreInit = TRUE`),
100 #' but it will run every other time.
101 #' }
102 #' \item{`ignoreNULL = TRUE` and `ignoreInit = TRUE`}{
103 #' This combination means that reactive/observer code will
104 #' *not* at the time of creation (because `ignoreInit = TRUE`).
105 #' After that, the reactive/observer code will run every time that
106 #' the event expression is not `NULL`.
107 #' }
108 #' }
109 #'
110
111 #' @section Types of objects:
112 #'
113 #' `bindEvent()` can be used with reactive expressions, observers, and shiny
114 #' render functions.
115 #'
116 #' When `bindEvent()` is used with `reactive()`, it creates a new reactive
117 #' expression object.
118 #'
119 #' When `bindEvent()` is used with `observe()`, it alters the observer in
120 #' place. It can only be used with observers which have not yet executed.
121 #'
122 #' @section Combining events and caching:
123 #'
124 #' In many cases, it makes sense to use `bindEvent()` along with
125 #' `bindCache()`, because they each can reduce the amount of work done on the
126 #' server. For example, you could have [sliderInput]s `x` and `y` and a
127 #' `reactive()` that performs a time-consuming operation with those values.
128 #' Using `bindCache()` can speed things up, especially if there are multiple
129 #' users. But it might make sense to also not do the computation until the
130 #' user sets both `x` and `y`, and then clicks on an [actionButton] named
131 #' `go`.
132 #'
133 #' To use both caching and events, the object should first be passed to
134 #' `bindCache()`, then `bindEvent()`. For example:
135
136 #'
137 #' ```
138 #' r <- reactive({
139 #' Sys.sleep(2) # Pretend this is an expensive computation
140 #' input$x * input$y
141 #' }) %>%
142 #' bindCache(input$x, input$y) %>%
143 #' bindEvent(input$go)
144 #' ```
145
146 #'
147 #' Anything that consumes `r()` will take a reactive dependency on the event
148 #' expression given to `bindEvent()`, and not the cache key expression given to
149 #' `bindCache()`. In this case, it is just `input$go`.
150 #'
151 #' @param x An object to wrap so that is triggered only when a the specified
152 #' event occurs.
153 #' @param ignoreNULL Whether the action should be triggered (or value
154 #' calculated) when the input is `NULL`. See Details.
155 #' @param ignoreInit If `TRUE`, then, when the eventified object is first
156 #' created/initialized, don't trigger the action or (compute the value). The
157 #' default is `FALSE`. See Details.
158 #' @param once Used only for observers. Whether this `observer` should be
159 #' immediately destroyed after the first time that the code in the observer is
160 #' run. This pattern is useful when you want to subscribe to a event that
161 #' should only happen once.
162 #' @param label A label for the observer or reactive, useful for debugging.
163 #' @param ... One or more expressions that represents the event; this can be a
164 #' simple reactive value like `input$click`, a call to a reactive expression
165 #' like `dataset()`, or even a complex expression inside curly braces. If
166 #' there are multiple expressions in the `...`, then it will take a dependency
167 #' on all of them.
168 #' @export
169 bindEvent <- function(x, ..., ignoreNULL = TRUE, ignoreInit = FALSE,
170 once = FALSE, label = NULL)
171 {
172 check_dots_unnamed()
173 force(ignoreNULL)
174 force(ignoreInit)
175 force(once)
176
177 UseMethod("bindEvent")
178 }
179
180
181 #' @export
182 bindEvent.default <- function(x, ...) {
183 stop("Don't know how to handle object with class ", paste(class(x), collapse = ", "))
184 }
185
186
187 #' @export
188 bindEvent.reactiveExpr <- function(x, ..., ignoreNULL = TRUE, ignoreInit = FALSE,
189 label = NULL)
190 {
191 domain <- reactive_get_domain(x)
192
193 qs <- enquos0(...)
194 eventFunc <- quos_to_func(qs)
195
196 valueFunc <- reactive_get_value_func(x)
197 valueFunc <- wrapFunctionLabel(valueFunc, "eventReactiveValueFunc", ..stacktraceon = TRUE)
198
199 call_srcref <- get_call_srcref(-1)
200 if (is.null(label)) {
201 label <- rassignSrcrefToLabel(
202 call_srcref,
203 defaultLabel = as_default_label(sprintf(
204 'bindEvent(%s, %s)',
205 attr(x, "observable", exact = TRUE)$.label,
206 quos_to_label(qs)
207 ))
208 )
209 }
210
211 x_classes <- class(x)
212 x_otel_attrs <- attr(x, "observable", exact = TRUE)$.otelAttrs
213
214 # Don't hold on to the reference for x, so that it can be GC'd
215 rm(x)
216
217 initialized <- FALSE
218
219 with_no_otel_collect({
220 res <- reactive(label = label, domain = domain, ..stacktraceon = FALSE, {
221 hybrid_chain(
222 {
223 eventFunc()
224 },
225 function(value) {
226 if (ignoreInit && !initialized) {
227 initialized <<- TRUE
228 req(FALSE)
229 }
230
231 req(!ignoreNULL || !isNullEvent(value))
232
233 isolate(valueFunc())
234 }
235 )
236 })
237 })
238
239 class(res) <- c("reactive.event", x_classes)
240
241 local({
242 impl <- attr(res, "observable", exact = TRUE)
243 impl$.otelAttrs <- append_otel_srcref_attrs(x_otel_attrs, call_srcref, fn_name = "bindEvent")
244 })
245
246
247 if (has_otel_collect("reactivity")) {
248 res <- enable_otel_reactive_expr(res)
249 }
250
251 res
252 }
253
254
255 #' @export
256 bindEvent.shiny.render.function <- function(x, ..., ignoreNULL = TRUE, ignoreInit = FALSE) {
257 eventFunc <- quos_to_func(enquos0(...))
258
259 valueFunc <- x
260
261 initialized <- FALSE
262
263 renderFunc <- function(...) {
264 hybrid_chain(
265 eventFunc(),
266 function(value) {
267 if (ignoreInit && !initialized) {
268 initialized <<- TRUE
269 req(FALSE)
270 }
271
272 req(!ignoreNULL || !isNullEvent(value))
273
274 isolate(valueFunc(...))
275 }
276 )
277 }
278
279 # Passes over the otelAttrs from valueFunc to renderFunc
280 renderFunc <- addAttributes(renderFunc, renderFunctionAttributes(valueFunc))
281 class(renderFunc) <- c("shiny.render.function.event", class(valueFunc))
282 renderFunc
283 }
284
285
286 #' @export
287 bindEvent.Observer <- function(x, ..., ignoreNULL = TRUE, ignoreInit = FALSE,
288 once = FALSE, label = NULL)
289 {
290 if (x$.execCount > 0) {
291 stop("Cannot call bindEvent() on an Observer that has already been executed.")
292 }
293
294 qs <- enquos0(...)
295 eventFunc <- quos_to_func(qs)
296 valueFunc <- x$.func
297
298 # Note that because the observer will already have been logged by this point,
299 # this updated label won't show up in the reactlog.
300 if (is.null(label)) {
301 call_srcref <- get_call_srcref(-1)
302 x$.label <- rassignSrcrefToLabel(
303 call_srcref,
304 defaultLabel = as_default_label(
305 sprintf('bindEvent(%s, %s)', x$.label, quos_to_label(qs))
306 )
307 )
308 } else {
309 x$.label <- label
310 }
311
312 initialized <- FALSE
313
314 x$.func <- wrapFunctionLabel(
315 name = x$.label,
316 ..stacktraceon = FALSE,
317 func = function() {
318 hybrid_chain(
319 eventFunc(),
320 function(value) {
321 if (ignoreInit && !initialized) {
322 initialized <<- TRUE
323 return()
324 }
325
326 if (ignoreNULL && isNullEvent(value)) {
327 return()
328 }
329
330 if (once) {
331 on.exit(x$destroy())
332 }
333
334 req(!ignoreNULL || !isNullEvent(value))
335
336 isolate(valueFunc())
337 }
338 )
339 }
340 )
341
342 class(x) <- c("Observer.event", class(x))
343 call_srcref <- get_call_srcref(-1)
344 x$.otelAttrs <- append_otel_srcref_attrs(x$.otelAttrs, call_srcref, fn_name = "bindEvent")
345
346 if (has_otel_collect("reactivity")) {
347 x <- enable_otel_observe(x)
348 }
349
350 invisible(x)
351 }
352
353
354 #' @export
355 bindEvent.reactive.event <- function(x, ...) {
356 stop("bindEvent() has already been called on the object.")
357 }
358
359 #' @export
360 bindEvent.Observer.event <- bindEvent.reactive.event