1.3.0 permalink Arrow_down_16x16

add-watch

clojure.core

  • (add-watch reference key fn)
Alpha - subject to change.
Adds a watch function to an agent/atom/var/ref 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, on the agent's thread if an agent,
before any pending sends if agent or ref. Note that an atom's or
ref's state may have changed again prior to the fn call, so use
old/new-state rather than derefing the reference. Note also that watch
fns may be called from multiple threads simultaneously. Var watchers
are triggered only by root binding changes, not thread-local
set!s. 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.

2 Examples top

  • ;; Add useful context to watcher function:
    (defn watch-agent [_agent context]
        (let [watch-fn (fn [_context _key _ref old-value new-value] ;...
                   )] 
            (add-watch _agent nil (partial watch-fn context))))
    
  • ;; timing of agent actions and watches using nrepl (ymmv)
    user> (def a (agent 0))
    #'user/a
    user> a
    #<Agent@2bd9c3e7: 0>
    user> (add-watch a :key (fn [k r os ns] (print k r os ns)))
    #<Agent@2bd9c3e7: 0>
    user> (send a inc)
    :key #<Agent@2bd9c3e7: 1> 0 1
    #<Agent@2bd9c3e7: 1>
    user> a
    :key #<Agent@2bd9c3e7: 2> 1 2
    #<Agent@2bd9c3e7: 2>
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:1909 top

(defn add-watch
  "Alpha - subject to change.
  Adds a watch function to an agent/atom/var/ref 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, on the agent's thread if an agent,
  before any pending sends if agent or ref. Note that an atom's or
  ref's state may have changed again prior to the fn call, so use
  old/new-state rather than derefing the reference. Note also that watch
  fns may be called from multiple threads simultaneously. Var watchers
  are triggered only by root binding changes, not thread-local
  set!s. 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."
  {:added "1.0"
   :static true}
  [^clojure.lang.IRef reference key fn] (.addWatch reference key fn))
Vars in clojure.core/add-watch:
Used in 0 other vars

Comments top

No comments for add-watch. Log in to add a comment.