Clojure Watcher

2018-12-27 18:44 更新

Watcher是添加到變量類型的函數(shù),例如atom和引用變量,當(dāng)變量類型的值改變時調(diào)用。 例如,如果調(diào)用程序更改atom變量的值,并且如果Watcher函數(shù)附加到atom變量,則一旦atom的值改變,該函數(shù)將被調(diào)用。

Clojure for Watchers中提供了以下功能。

添加Watcher

向agent / atom / var / ref引用添加watch函數(shù)。 手表'fn'必須是4個參數(shù)的'fn':一個鍵,引用,它的舊狀態(tài),它的新狀態(tài)。 每當(dāng)引用的狀態(tài)可能已更改,任何注冊的手表都將調(diào)用其函數(shù)。

語法

以下是 Watcher 基本使用語法:

(add-watch variable :watcher
   (fn [key variable-type old-state new-state]))

參數(shù) - 'variable'是原子或引用變量的名稱。 'variable-type'是變量的類型,原子或引用變量。 '舊狀態(tài)和新狀態(tài)'是將自動保存變量的舊值和新值的參數(shù)。 'key'對于每個引用必須是唯一的,并且可以用于刪除帶有remove-watch的手表。

返回值 -無。

下面是一個 Watcher 使用的例子。

(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

移除Watcher

除去已附著在引用變量的手表。

語法

以下是 移除Watcher 基本使用語法:

(remove-watch variable watchname)

參數(shù) - 'variable'是atom或引用變量的名稱。 'watchname'是定義監(jiān)視功能時給Watcher 的名稱。

返回值 -無。

下面是一個 移除Watcher的例子。
(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

從上面的程序可以清楚地看到,第二個重置命令不會觸發(fā)觀察者,因為它被從觀察者的列表中刪除。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號