On Mar 11, 11:20 am, linh <nguyenlinh.m...@gmail.com> wrote:

> According to the API doc, add-watch must have 4 args: a key, a
> reference,
> its old-state and its new state. What I'm missing here is an addtional
> arg that can be passed in some way to update-fn so that update-fn
> knows what entries in my-atom has changed.
> Is there any way do this?


well you could always add a key :last-update containing the key
changed in the last update. Then your add-watch update function just
reads this key and knows what's been modified. To accomplish this of
course, in your

(swap! my-atom (some-fn...

some-fn would have to include code that  sets the :last-update value
when done. Here's a sketch:

;; this just makes a big map atom where integer keys are associated
with integer values

(def my-atom
     (atom (assoc (apply hash-map
                         (take 1000
                               (interleave
                                (iterate inc 0)
                                (iterate inc 100))))
             :last-update nil)))


;; this adds a watcher that knows what's been changed
;; by reading the :last-update key and prints it out

(add-watch my-atom :update-watcher
           (fn [me my-atom old new]
             (println "this key was updated" (:last-update new))))


;; this is the update-function that both changes the desired key
;; and val and also updates the :last-update key

(defn my-atom-swapper [the-atom key newval]
  (let [changed-atom (assoc the-atom key newval)]
    (assoc changed-atom :last-update key)))

;; a simple test

(defn test-update-watcher []
  (swap! my-atom my-atom-swapper :10 "ten")
  (:10 @my-atom))
--~--~---------~--~----~------------~-------~--~----~
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