Debian Codegraph @

man/ExtendedTask.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/extended-task.R
3 \name{ExtendedTask}
4 \alias{ExtendedTask}
5 \title{Task or computation that proceeds in the background}
6 \description{
7 In normal Shiny reactive code, whenever an observer, calc, or
8 output is busy computing, it blocks the current session from receiving any
9 inputs or attempting to proceed with any other computation related to that
10 session.
11
12 The \code{ExtendedTask} class allows you to have an expensive operation that is
13 started by a reactive effect, and whose (eventual) results can be accessed
14 by a regular observer, calc, or output; but during the course of the
15 operation, the current session is completely unblocked, allowing the user
16 to continue using the rest of the app while the operation proceeds in the
17 background.
18
19 Note that each \code{ExtendedTask} object does not represent a \emph{single
20 invocation} of its long-running function. Rather, it's an object that is
21 used to invoke the function with different arguments, keeps track of
22 whether an invocation is in progress, and provides ways to get at the
23 current status or results of the operation. A single \code{ExtendedTask} object
24 does not permit overlapping invocations: if the \code{invoke()} method is called
25 before the previous \code{invoke()} is completed, the new invocation will not
26 begin until the previous invocation has completed.
27 }
28 \section{\code{ExtendedTask} versus asynchronous reactives}{
29
30
31 Shiny has long supported \href{https://rstudio.github.io/promises/articles/promises_06_shiny.html}{using \{promises\}}
32 to write asynchronous observers, calcs, or outputs. You may be wondering
33 what the differences are between those techniques and this class.
34
35 Asynchronous observers, calcs, and outputs are not--and have never
36 been--designed to let a user start a long-running operation, while keeping
37 that very same (browser) session responsive to other interactions. Instead,
38 they unblock other sessions, so you can take a long-running operation that
39 would normally bring the entire R process to a halt and limit the blocking
40 to just the session that started the operation. (For more details, see the
41 section on \href{https://rstudio.github.io/promises/articles/promises_06_shiny.html#the-flush-cycle}{"The Flush Cycle"}.)
42
43 \code{ExtendedTask}, on the other hand, invokes an asynchronous function (that
44 is, a function that quickly returns a promise) and allows even that very
45 session to immediately unblock and carry on with other user interactions.
46 }
47
48 \section{OpenTelemetry Integration}{
49
50
51 When an \code{ExtendedTask} is created, if OpenTelemetry tracing is enabled for
52 \code{"reactivity"} (see \code{\link[=withOtelCollect]{withOtelCollect()}}), the \code{ExtendedTask} will record
53 spans for each invocation of the task. The tracing level at \code{invoke()} time
54 does not affect whether spans are recorded; only the tracing level when
55 calling \code{ExtendedTask$new()} matters.
56
57 The OTel span will be named based on the label created from the variable the
58 \code{ExtendedTask} is assigned to. If no label can be determined, the span will
59 be named \verb{<anonymous>}. Similar to other Shiny OpenTelemetry spans, the span
60 will also include source reference attributes and session ID attributes.
61
62 \if{html}{\out{<div class="sourceCode r">}}\preformatted{withOtelCollect("all", \{
63 my_task <- ExtendedTask$new(function(...) \{ ... \})
64 \})
65
66 # Span recorded for this invocation: ExtendedTask my_task
67 my_task$invoke(...)
68 }\if{html}{\out{</div>}}
69 }
70
71 \examples{
72 \dontshow{if (rlang::is_interactive() && rlang::is_installed("mirai")) withAutoprint(\{ # examplesIf}
73 library(shiny)
74 library(bslib)
75 library(mirai)
76
77 # Set background processes for running tasks
78 daemons(1)
79 # Reset when the app is stopped
80 onStop(function() daemons(0))
81
82 ui <- page_fluid(
83 titlePanel("Extended Task Demo"),
84 p(
85 'Click the button below to perform a "calculation"',
86 "that takes a while to perform."
87 ),
88 input_task_button("recalculate", "Recalculate"),
89 p(textOutput("result"))
90 )
91
92 server <- function(input, output) {
93 rand_task <- ExtendedTask$new(function() {
94 mirai(
95 {
96 # Slow operation goes here
97 Sys.sleep(2)
98 sample(1:100, 1)
99 }
100 )
101 })
102
103 # Make button state reflect task.
104 # If using R >=4.1, you can do this instead:
105 # rand_task <- ExtendedTask$new(...) |> bind_task_button("recalculate")
106 bind_task_button(rand_task, "recalculate")
107
108 observeEvent(input$recalculate, {
109 # Invoke the extended in an observer
110 rand_task$invoke()
111 })
112
113 output$result <- renderText({
114 # React to updated results when the task completes
115 number <- rand_task$result()
116 paste0("Your number is ", number, ".")
117 })
118 }
119
120 shinyApp(ui, server)
121 \dontshow{\}) # examplesIf}
122 }
123 \section{Methods}{
124 \subsection{Public methods}{
125 \itemize{
126 \item \href{#method-ExtendedTask-new}{\code{ExtendedTask$new()}}
127 \item \href{#method-ExtendedTask-invoke}{\code{ExtendedTask$invoke()}}
128 \item \href{#method-ExtendedTask-status}{\code{ExtendedTask$status()}}
129 \item \href{#method-ExtendedTask-result}{\code{ExtendedTask$result()}}
130 }
131 }
132 \if{html}{\out{<hr>}}
133 \if{html}{\out{<a id="method-ExtendedTask-new"></a>}}
134 \if{latex}{\out{\hypertarget{method-ExtendedTask-new}{}}}
135 \subsection{Method \code{new()}}{
136 Creates a new \code{ExtendedTask} object. \code{ExtendedTask} should generally be
137 created either at the top of a server function, or at the top of a module
138 server function.
139 \subsection{Usage}{
140 \if{html}{\out{<div class="r">}}\preformatted{ExtendedTask$new(func)}\if{html}{\out{</div>}}
141 }
142
143 \subsection{Arguments}{
144 \if{html}{\out{<div class="arguments">}}
145 \describe{
146 \item{\code{func}}{The long-running operation to execute. This should be an
147 asynchronous function, meaning, it should use the
148 \href{https://rstudio.github.io/promises/}{\{promises\}} package, most
149 likely in conjunction with the
150 \href{https://mirai.r-lib.org}{\{mirai\}} or
151 \href{https://rstudio.github.io/promises/articles/promises_04_futures.html}{\{future\}}
152 package. (In short, the return value of \code{func} should be a
153 \code{\link[mirai:mirai]{mirai}}, \code{\link[future:future]{Future}}, \code{promise},
154 or something else that \code{\link[promises:is.promise]{promises::as.promise()}} understands.)
155
156 It's also important that this logic does not read from any
157 reactive inputs/sources, as inputs may change after the function is
158 invoked; instead, if the function needs to access reactive inputs, it
159 should take parameters and the caller of the \code{invoke()} method should
160 read reactive inputs and pass them as arguments.}
161 }
162 \if{html}{\out{</div>}}
163 }
164 }
165 \if{html}{\out{<hr>}}
166 \if{html}{\out{<a id="method-ExtendedTask-invoke"></a>}}
167 \if{latex}{\out{\hypertarget{method-ExtendedTask-invoke}{}}}
168 \subsection{Method \code{invoke()}}{
169 Starts executing the long-running operation. If this \code{ExtendedTask} is
170 already running (meaning, a previous call to \code{invoke()} is not yet
171 complete) then enqueues this invocation until after the current
172 invocation, and any already-enqueued invocation, completes.
173 \subsection{Usage}{
174 \if{html}{\out{<div class="r">}}\preformatted{ExtendedTask$invoke(...)}\if{html}{\out{</div>}}
175 }
176
177 \subsection{Arguments}{
178 \if{html}{\out{<div class="arguments">}}
179 \describe{
180 \item{\code{...}}{Parameters to use for this invocation of the underlying
181 function. If reactive inputs are needed by the underlying function,
182 they should be read by the caller of \code{invoke} and passed in as
183 arguments.}
184 }
185 \if{html}{\out{</div>}}
186 }
187 }
188 \if{html}{\out{<hr>}}
189 \if{html}{\out{<a id="method-ExtendedTask-status"></a>}}
190 \if{latex}{\out{\hypertarget{method-ExtendedTask-status}{}}}
191 \subsection{Method \code{status()}}{
192 This is a reactive read that invalidates the caller when the task's
193 status changes.
194
195 Returns one of the following values:
196 \itemize{
197 \item \code{"initial"}: This \code{ExtendedTask} has not yet been invoked
198 \item \code{"running"}: An invocation is currently running
199 \item \code{"success"}: An invocation completed successfully, and a value can be
200 retrieved via the \code{result()} method
201 \item \code{"error"}: An invocation completed with an error, which will be
202 re-thrown if you call the \code{result()} method
203 }
204 \subsection{Usage}{
205 \if{html}{\out{<div class="r">}}\preformatted{ExtendedTask$status()}\if{html}{\out{</div>}}
206 }
207
208 }
209 \if{html}{\out{<hr>}}
210 \if{html}{\out{<a id="method-ExtendedTask-result"></a>}}
211 \if{latex}{\out{\hypertarget{method-ExtendedTask-result}{}}}
212 \subsection{Method \code{result()}}{
213 Attempts to read the results of the most recent invocation. This is a
214 reactive read that invalidates as the task's status changes.
215
216 The actual behavior differs greatly depending on the current status of
217 the task:
218 \itemize{
219 \item \code{"initial"}: Throws a silent error (like \code{\link[=req]{req(FALSE)}}). If
220 this happens during output rendering, the output will be blanked out.
221 \item \code{"running"}: Throws a special silent error that, if it happens during
222 output rendering, makes the output appear "in progress" until further
223 notice.
224 \item \code{"success"}: Returns the return value of the most recent invocation.
225 \item \code{"error"}: Throws whatever error was thrown by the most recent
226 invocation.
227 }
228
229 This method is intended to be called fairly naively by any output or
230 reactive expression that cares about the output--you just have to be
231 aware that if the result isn't ready for whatever reason, processing will
232 stop in much the same way as \code{req(FALSE)} does, but when the result is
233 ready you'll get invalidated, and when you run again the result should be
234 there.
235
236 Note that the \code{result()} method is generally not meant to be used with
237 \code{\link[=observeEvent]{observeEvent()}}, \code{\link[=eventReactive]{eventReactive()}}, \code{\link[=bindEvent]{bindEvent()}}, or \code{\link[=isolate]{isolate()}} as the
238 invalidation will be ignored.
239 \subsection{Usage}{
240 \if{html}{\out{<div class="r">}}\preformatted{ExtendedTask$result()}\if{html}{\out{</div>}}
241 }
242
243 }
244 }