This question is related to this one. The two can generate the same functionality, but implementation is slightly different. One significant difference is that a reactiveValue
is a container that can have several values, like input$
. In shiny documentation functionality is usually implemented using reactive()
, but in most cases I find reactiveValues()
more convenient. Is there any catch here? Are there any other major differences between the two that I might not be aware off? Are these two code snippets equivalent?
See the same example code implemented using:
a reactive expression:
library(shiny) ui <- fluidPage( shiny::numericInput(inputId = 'n',label = 'n',value = 2), shiny::textOutput('nthValue'), shiny::textOutput('nthValueInv') ) fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2)) server<-shinyServer(function(input, output, session) { currentFib <- reactive({ fib(as.numeric(input$n)) }) output$nthValue <- renderText({ currentFib() }) output$nthValueInv <- renderText({ 1 / currentFib() }) }) shinyApp(ui = ui, server = server)
a reactive value:
library(shiny) ui <- fluidPage( shiny::numericInput(inputId = 'n',label = 'n',value = 2), shiny::textOutput('nthValue'), shiny::textOutput('nthValueInv') ) fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2)) server<-shinyServer(function(input, output, session) { myReactives <- reactiveValues() observe( myReactives$currentFib <- fib(as.numeric(input$n)) ) output$nthValue <- renderText({ myReactives$currentFib }) output$nthValueInv <- renderText({ 1 / myReactives$currentFib }) }) shinyApp(ui = ui, server = server)