Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does observeEvent don't re-evaluate it's content?

Tags:

r

shiny

In the following example, the text is not shown in the start. If I click on the "show"-Button the text appears. If I then click on the "hide"-Button nothing else happens anymore. In fact the "textis$visible" variable has always the correct value, but i think the if-statement in the observeEvent funktion is only calculated after the very first button click.

Is there a way to force observeEvent to re-evaluate the if statement? Or are there other ways to stop shiny from executing code in the server part and restart it again (in the real case there would be a whole bunch of function calls inside the if statement, not just hide and show some text)

library(shiny)

ui <- fluidPage(

actionButton(inputId="show","show"),
actionButton(inputId="hide","hide"),

textOutput(outputId = "some_text")
)


server <- function(input, output) {

  textis<-reactiveValues(visible=FALSE)

observeEvent(input$show,
             textis$visible<-TRUE)

observeEvent(input$hide,
             textis$visible<-FALSE)

observeEvent(textis$visible  , if(textis$visible){
  output$some_text<-renderText({"this is some text"})  
})}

shinyApp(ui = ui, server = server)
like image 627
alfred j. quak Avatar asked Sep 16 '25 08:09

alfred j. quak


1 Answers

The observeEvent expressions are evaluated any time the value of their event expression changes. But, in the code you have above, when textis$visible changes, the observer only has instructions to perform if textis$visible is true. In the code snippet below, I've used else{...} to give that observer an action to perform when testis$visible is not true.

  observeEvent(textis$visible  , if(textis$visible){
    output$some_text<-renderText({"this is some text"})  
  } else {output$some_text<-renderText({''}) }
  )}

So, if you paste the else clause above into your app, the output some_text will disappear when the hide button is clicked.

like image 170
Alex P Avatar answered Sep 19 '25 03:09

Alex P