Adrarc
Adrarc

Reputation: 151

Return list of all active observers in a Shiny app?

While using browser() with an active Shiny app, I can get a vector of all the inputs created using:
reactiveValuesToList(input) %>% names()

I can also get a vector of all the output names created using:
outputOptions(output) %>% names()

But what about if I want to get a list/vector of all the active observers?
Say make an actionButton with id = mybutton1, it will appear in the list of all inputs.
Now, I create an observer for mybutton1:

observeEvent(input$mybutton1, {
     print("Button clicked!")
})

This observer is now created, right?
Is there a way I can access the list of observers with something like obs$names or getObs() ? (I'm making these up).
If there is, can I simply get the name of an observer to destroy it? rm(obs$mybutton1) or destroy(obs$mybutton1).

Upvotes: 3

Views: 413

Answers (1)

Stéphane Laurent
Stéphane Laurent

Reputation: 84709

An observer has the class Observer, and you can assign an observer to a variable:

library(shiny)

values <- reactiveValues(A = 1)

obsB <- observe({
  print(values$A + 1)
})
obsC <- observe({
  print(values$A * 2)
})

Then you can get the names of all variables storing an observer as follows:

Filter(function(x) inherits(get(x), "Observer"), ls())
# "obsB" "obsC"

An observer is also a R6 object, and it has a method destroy():

obsB$destroy()

But destroying an observer does not remove it:

Filter(function(x) inherits(get(x), "Observer"), ls())
# "obsB" "obsC"

It will not observe anymore, that's all. So you have to use rm if needed.

Upvotes: 2

Related Questions