向agent / atom / var / ref引用添加watch函數(shù)。 手表'fn'必須是4個(gè)參數(shù)的'fn':一個(gè)鍵,引用,它的舊狀態(tài),它的新?tīng)顟B(tài)。 每當(dāng)引用的狀態(tài)可能已更改,任何注冊(cè)的手表都將調(diào)用其函數(shù)。
(ns clojure.examples.example
(:gen-class))
(defn Example []
(def x (atom 0))
(add-watch x :watcher
(fn [key atom old-state new-state]
(println "The value of the atom has been changed")
(println "old-state" old-state)
(println "new-state" new-state)))
(reset! x 2))
(Example)
輸出
以上示例輸出以下結(jié)果:
The value of the atom has been changed
old-state 0
new-state 2
(ns clojure.examples.example
(:gen-class))
(defn Example []
(def x (atom 0))
(add-watch x :watcher
(fn [key atom old-state new-state]
(println "The value of the atom has been changed")
(println "old-state" old-state)
(println "new-state" new-state)))
(reset! x 2)
(remove-watch x :watcher)
(reset! x 4))
(Example)
輸出
以上示例輸出以下結(jié)果:
The value of the atom has been changed
old-state 0
new-state 2
更多建議: