| 1 |
% Generated by roxygen2: do not edit by hand |
| 2 |
% Please edit documentation in R/reactives.R |
| 3 |
\name{reactiveVal} |
| 4 |
\alias{reactiveVal} |
| 5 |
\title{Create a (single) reactive value} |
| 6 |
\usage{ |
| 7 |
reactiveVal(value = NULL, label = NULL) |
| 8 |
} |
| 9 |
\arguments{ |
| 10 |
\item{value}{An optional initial value.} |
| 11 |
|
| 12 |
\item{label}{An optional label, for debugging purposes (see |
| 13 |
\code{\link[=reactlog]{reactlog()}}). If missing, a label will be automatically |
| 14 |
created.} |
| 15 |
} |
| 16 |
\value{ |
| 17 |
A function. Call the function with no arguments to (reactively) read |
| 18 |
the value; call the function with a single argument to set the value. |
| 19 |
} |
| 20 |
\description{ |
| 21 |
The \code{reactiveVal} function is used to construct a "reactive value" |
| 22 |
object. This is an object used for reading and writing a value, like a |
| 23 |
variable, but with special capabilities for reactive programming. When you |
| 24 |
read the value out of a reactiveVal object, the calling reactive expression |
| 25 |
takes a dependency, and when you change the value, it notifies any reactives |
| 26 |
that previously depended on that value. |
| 27 |
} |
| 28 |
\details{ |
| 29 |
\code{reactiveVal} is very similar to \code{\link[=reactiveValues]{reactiveValues()}}, except |
| 30 |
that the former is for a single reactive value (like a variable), whereas the |
| 31 |
latter lets you conveniently use multiple reactive values by name (like a |
| 32 |
named list of variables). For a one-off reactive value, it's more natural to |
| 33 |
use \code{reactiveVal}. See the Examples section for an illustration. |
| 34 |
} |
| 35 |
\examples{ |
| 36 |
|
| 37 |
\dontrun{ |
| 38 |
|
| 39 |
# Create the object by calling reactiveVal |
| 40 |
r <- reactiveVal() |
| 41 |
|
| 42 |
# Set the value by calling with an argument |
| 43 |
r(10) |
| 44 |
|
| 45 |
# Read the value by calling without arguments |
| 46 |
r() |
| 47 |
|
| 48 |
} |
| 49 |
|
| 50 |
## Only run examples in interactive R sessions |
| 51 |
if (interactive()) { |
| 52 |
|
| 53 |
ui <- fluidPage( |
| 54 |
actionButton("minus", "-1"), |
| 55 |
actionButton("plus", "+1"), |
| 56 |
br(), |
| 57 |
textOutput("value") |
| 58 |
) |
| 59 |
|
| 60 |
# The comments below show the equivalent logic using reactiveValues() |
| 61 |
server <- function(input, output, session) { |
| 62 |
value <- reactiveVal(0) # rv <- reactiveValues(value = 0) |
| 63 |
|
| 64 |
observeEvent(input$minus, { |
| 65 |
newValue <- value() - 1 # newValue <- rv$value - 1 |
| 66 |
value(newValue) # rv$value <- newValue |
| 67 |
}) |
| 68 |
|
| 69 |
observeEvent(input$plus, { |
| 70 |
newValue <- value() + 1 # newValue <- rv$value + 1 |
| 71 |
value(newValue) # rv$value <- newValue |
| 72 |
}) |
| 73 |
|
| 74 |
output$value <- renderText({ |
| 75 |
value() # rv$value |
| 76 |
}) |
| 77 |
} |
| 78 |
|
| 79 |
shinyApp(ui, server) |
| 80 |
|
| 81 |
} |
| 82 |
|
| 83 |
} |