add-watch

functionsince v0.0-927 clojure.core/add-watchEdit
(add-watch iref key f)

Details:

Adds a watch function f to atom a that will execute when the value of a changes.

The watch function takes 4 arguments: a key, the atom, its old state, and its new state.

key should be a keyword and can be used with remove-watch to remove the watch function.


Examples:

(def a (atom {}))

(add-watch a :logger
  (fn [_key _atom old-state new-state]
    (println "old:" old-state)
    (println "new:" new-state)))

(swap! a assoc :foo "bar")
;;=> will print the following:
;; old: {}
;; new: {:foo "bar"}

See Also:


Source docstring:
Adds a watch function to an atom reference. The watch fn must be a
fn of 4 args: a key, the reference, its old-state, its
new-state. Whenever the reference's state might have been changed,
any registered watches will have their functions called. The watch
fn will be called synchronously. Note that an atom's state
may have changed again prior to the fn call, so use old/new-state
rather than derefing the reference. Keys must be unique per
reference, and can be used to remove the watch with remove-watch,
but are otherwise considered opaque by the watch mechanism.  Bear in
mind that regardless of the result or action of the watch fns the
atom's value will change.  Example:

    (def a (atom 0))
    (add-watch a :inc (fn [k r o n] (assert (== 0 n))))
    (swap! a inc)
    ;; Assertion Error
    (deref a)
    ;=> 1
Source code @ clojurescript:src/main/cljs/cljs/core.cljs
(defn add-watch
  [iref key f]
  (-add-watch iref key f)
  iref)