Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way of getting all the keys of the watches in clojure

Tags:

clojure

If there was an atom:

(def a (atom {}))

with the following watches set

(add-watch a :watcher println)
(add-watch a :watcher2 println)

is there a function like this?

(get-watches a)
;; => [:watcher :watcher2]
like image 647
zcaudate Avatar asked Oct 10 '12 07:10

zcaudate


2 Answers

(atom {}) creates an object of type clojure.lang.Atom which extends abstract class clojure.lang.ARef which implements clojure.lang.IRef interface. IRef declares method getWatches that is implemented in ARef.

Here's the solution:

(def a (atom {}))
(add-watch a :watcher println)
(println (-> a .getWatches keys))

It is strange that clojure.core doesn't have get-watches. Mirroring add-watch implementation we get:

(defn get-watches 
  "Returns list of keys corresponding to watchers of the reference."
  [^clojure.lang.IRef reference] 
  (keys (.getWatches reference)))
like image 57
Ivan Koblik Avatar answered Sep 30 '22 18:09

Ivan Koblik


Ivan's answer is great for Clojure on the JVM. Here's how you do it in ClojureScript:

(keys (.-watches a))

like image 24
Daniel Glauser Avatar answered Sep 30 '22 19:09

Daniel Glauser