Reputation: 1723
How can I overwrite/re-define a reactive expression, while keeping all observers to that expression intact?
Below example is intended to make the observer listen to a button click, but only after the button has been clicked once. Before that, the observer should react to a numeric input field. (Please note that I would like the observer untouched if possible. I would like to re-define the reactive expression instead.)
library(shiny)
ui <- fluidPage(
numericInput(inputId="some_numbers",value=8,label = "Enter a number:"),
actionButton(inputId = "button1",label="Update reactive expression")
)
server <- function(input, output, session) {
my_reactive_expr <- reactive({
input$some_numbers
})
observeEvent(my_reactive_expr(),{
print("reactive value change detected!")
})
observeEvent(input$button1,{
my_reactive_expr <<- reactive({
input$button1
})
})
}
shinyApp(ui = ui, server = server)
Upvotes: 0
Views: 717
Reputation: 17689
Like written in the comments i would suggest sthg like:
my_reactive_expr <- reactive({
if(!input$button1) return(input$some_numbers)
input$button1
})
The full app would read:
library(shiny)
ui <- fluidPage(
numericInput(inputId="some_numbers",value=8,label = "Enter a number:"),
actionButton(inputId = "button1",label="Update reactive expression")
)
server <- function(input, output, session) {
my_reactive_expr <- reactive({
if(!input$button1) return(input$some_numbers)
input$button1
})
observeEvent(my_reactive_expr(),{
print("reactive value change detected!")
})
observeEvent(input$button1,{
my_reactive_expr <<- reactive({
input$button1
})
})
}
shinyApp(ui = ui, server = server)
Like that you can avoid overwriting the reactive function.
Upvotes: 2