Skip to content

clojure.core/add-watch

View this page on ClojureDocs

Type: function Added: Clojure 1.0 Examples: 5 Runnable: 3
([reference key fn])

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.

Examples

by devijvers on
by Daniel Brotsky on . May have evaluation errors.
by zk on
by EfrainBergillos on
by jkxyz on . May have evaluation errors.

Note by hura

One "gotcha" is that atoms add-watches do not always guarantee order semantics. So if you have a watch put [old-val new-val] on a channel, and your atom operation is something like (swap! a inc), you may see values in your channel like this:

[0 1]
[2 3]
[1 2]
[3 4]
[6 7]
[4 5]

This is because the watches are dispatched in different threads.

Source

See also


Content from the matching ClojureDocs page, with authors credited on each contribution.