Watchers 是添加到变量类型的函数,如原子和引用变量,这些变量在变量类型的值更改时被调用,如果调用程序更改了atom变量的值,并且将观察者函数附加到atom变量,则一旦atom的值更改,该函数就会被调用。
Clojure for Watchers中提供以下函数。
将观察函数添加到agent/atom/var/ref,观察者 “ fn”必须是4个参数的“ fn”:key,variable-type,old-state,new-state,只要被观察的状态变更,任何已注册的都会调用其函数。
(add-watch variable :watcher (fn [key variable-type old-state new-state]))
参数 - “variable”是原子或引用变量的名称, “varible-type”是原子或参考变量的类型,“old-state & new-state”是将自动保存变量的新旧值的参数, 每个参考的“key”必须唯一,并且可用于通过remove-watch 。
返回值 - 无。
(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)
上面的程序产生以下输出。
The value of the atom has been changed old-state 0 new-state 2
(remove-watch variable watchname)
(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)
上面的程序产生以下输出。
The value of the atom has been changed old-state 0 new-state 2
您可以从上面的程序中清楚地看到第二个重置命令不会触发观察者,因为它已从观察者列表中删除。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Spring Boot与Kubernetes云原生微服务实践 -〔杨波〕