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