Skip to content

Instantly share code, notes, and snippets.

@attentive
Created May 5, 2017 04:09
Show Gist options
  • Save attentive/688760828a0e0cda588a1393466f1266 to your computer and use it in GitHub Desktop.
Save attentive/688760828a0e0cda588a1393466f1266 to your computer and use it in GitHub Desktop.
Using Clojure add-watch to track the previous state of an atom
(def current (atom 1))
(def previous (atom nil))
(add-watch current :dontcare
(fn [_ _ old-state _]
(reset! previous old-state)))
(repeatedly 10 #(do (swap! current * 2)
(println "Current:" @current "Previous:" @previous)))
;Current: 2 Previous: 1
;Current: 4 Previous: 2
;Current: 8 Previous: 4
;Current: 16 Previous: 8
;Current: 32 Previous: 16
;Current: 64 Previous: 32
;Current: 128 Previous: 64
;Current: 256 Previous: 128
;Current: 512 Previous: 256
;Current: 1024 Previous: 512
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment