Clojure - Watches and Validators

1 minute read

Watches and Validators

Watches allow us to monitor every atom change and validators allow us to validate that change.

Watches

Watches are just functions that take four arguments: a key, the referene being watched, its previous state, and its new state. Here is an example of a watch that prints whenever an atom changes its value.

1(def count (atom 0))
2
3(add-watch count :counter (fn [key atom old-val new-val]
4                              (println "Value of " key " has changed from " old-val " to " new-val)))
5
6(swap! count inc)
7; => Value of :counter has changed from 0 to 1
8; => 1

Validators

Validators specify what states are allowable for a reference. For example here is a validator that allows only odd values:

1(def count (atom 0))
2
3(set-validator! count odd?)
4
5(swap! count inc)
6; => 1
7
8(swap! count inc)
9; => Invalid reference state