Hen*_*gon 7 history clojure stm
鉴于STM拥有refs,agent等10个值的历史记录,可以读取这些值吗?
原因是,我正在更新一堆代理商,我需要保留价值历史.如果STM已经保留它们,我宁愿只使用它们.我在API中找不到看起来像是从STM历史中读取值的函数,所以我猜不是,也不能在java源代码中找到任何方法,但也许我看起来不对.
您无法直接访问值的stm历史记录.但是您可以使用add-watch来记录值的历史记录:
(def a-history (ref []))
(def a (agent 0))
(add-watch a :my-history
(fn [key ref old new] (alter a-history conj old)))
Run Code Online (Sandbox Code Playgroud)
每次a更新(stm事务提交)时,旧值将被合并到保留的序列中a-history.
如果要访问所有中间值,即使对于回滚事务,您也可以在事务期间将值发送给代理:
(def r-history (agent [])
(def r (ref 0))
(dosync (alter r
(fn [new-val]
(send r-history conj new-val) ;; record potential new value
(inc r)))) ;; update ref as you like
Run Code Online (Sandbox Code Playgroud)
事务完成后,r-history将执行对代理的所有更改.