Are objects created inside observeEvent block of code accessible after it?

Hello! I have a question.

In my shiny app, I have two action buttons in on the ui side.

On my server side, I have two corresponding observeEvent blocks of code.
The first block 'observes' what happens to action button 1:

firstblock <- observeEvent(input$button1_pressed, { do stuff, create objects })

The second block 'observes' what happens to action button 2.

secondblock <- observeEvent(input$button2_pressed, { use objects created in firstblock })

Let's assume that the user first clicks on action button 1, and only then on action button 2.

Question: Are objects created inside firstblock accessible directly under their names in secondblock? For example, if inside firstblock I created object1, can I "do things" to object1 in secondblock?

Thank you very much!

1 Like

So observeEvent() is like eventReactive() in that it is a function so it creates its own environment and executes the code with the same scoping rules as functions. However, observeEvent and eventReactive are different in that observeEvent is supposed to execute code based on changes without returning anything and eventReactive executes its code and returns an object. If you want to use an object from firstblock you should change it to an eventReactive and explicitly return something. You can then access the return object in secondblock by calling firstblock(). The parenthesis are important when calling firstblock() as it is essentially a function with no arguments, so you need to call it like one.

1 Like

Thank you very much! So, if I understood you correctly: what happens inside observeEven() stays there - so that the objects created there are NOT accessible to any other observeEvent block?

Yes. observe and observeEvent are both supposed to be used to react to changes in your app and trigger side effects. Whereas reactive and eventReactive are meant to react to changes in your app and return some kind of R object that can then be used in the rest of the server side code (such as other reactive functions, observe functions, and outputs).

You can check out this SO post for some good explanations between the differences