The code below registers a watcher with a Var, a Ref and an Atom.
The watch Agent has a map value that is used to count the number of
times each thing it is watching changes.
The keys are reference objects and the values are change counts.
The code correctly reports two changes to the Ref, three changes to
the Atom, but nil changes to the Var.
However, when I output the Var, it's clear that it changed.
Maybe I'm registering it incorrectly. Do I need to pass (var my-var)
to add-watcher?

(def my-watcher (agent {}))

(defn my-watcher-action [current-value reference]
  (let [change-count-map current-value
        old-count (change-count-map reference)
        new-count (if old-count (inc old-count) 1)]
  (assoc change-count-map reference new-count)))

(def my-var "v1")
(def my-ref (ref "r1"))
(def my-atom (atom "a1"))

(add-watcher (var my-var) :send my-watcher my-watcher-action)
(add-watcher my-ref :send my-watcher my-watcher-action)
(add-watcher my-atom :send my-watcher my-watcher-action)

(alter-var-root (var my-var) (fn [curr-val] "v2"))
; The change happens, but the watcher doesn't see it!
(println "my-var is now" my-var)

(dosync
  ; The next line only changes the in-transaction value
  ; so the watcher isn't notified.
  (ref-set my-ref "r2")
  (ref-set my-ref "r3")) ; Now the watcher is notified of one change.
(dosync
  (ref-set my-ref "r4")) ; And now one more.

(reset! my-atom "a2")
(reset! my-atom "a3")
(reset! my-atom "a4")

(let [change-count-map @my-watcher]
  (println "my-var changes =" (change-count-map my-var))
  (println "my-ref changes =" (change-count-map my-ref))
  (println "my-atom changes =" (change-count-map my-atom)))

(await my-watcher)
(shutdown-agents)

-- 
R. Mark Volkmann
Object Computing, Inc.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to