Clojure - 观察者

Clojure - 观察者 首页 / Clojure入门教程 / Clojure - 观察者

Watchers 是添加到变量类型的函数,如原子和引用变量,这些变量在变量类型的值更改时被调用,如果调用程序更改了atom变量的值,并且将观察者函数附加到atom变量,则一旦atom的值更改,该函数就会被调用。

Clojure for Watchers中提供以下函数。

add-watch

观察函数添加到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)

上面的程序产生以下输出。

链接:https://www.learnfk.comhttps://www.learnfk.com/clojure/clojure-watchers.html

来源:LearnFk无涯教程网

The value of the atom has been changed
old-state 0
new-state 2

remove-watch

(remove-watch variable watchname)

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)
   (remove-watch x :watcher)
(reset! x 4))
(Example)

上面的程序产生以下输出。

链接:https://www.learnfk.comhttps://www.learnfk.com/clojure/clojure-watchers.html

来源:LearnFk无涯教程网

The value of the atom has been changed
old-state 0
new-state 2

您可以从上面的程序中清楚地看到第二个重置命令不会触发观察者,因为它已从观察者列表中删除。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

玩转webpack -〔程柳锋〕

架构实战案例解析 -〔王庆友〕

HarmonyOS快速入门与实战 -〔QCon+案例研习社〕

深入C语言和程序运行原理 -〔于航〕

Web 3.0入局攻略 -〔郭大治〕

深入浅出可观测性 -〔翁一磊〕

超级访谈:对话毕玄 -〔毕玄〕

零基础学Python(2023版) -〔尹会生〕

零基础GPT应用入门课 -〔林健(键盘)〕

好记忆不如烂笔头。留下您的足迹吧 :)