Clojure 状态管理:Atoms、Agents 和 Vars 的使用
1. 使用 Atoms 进行无协调的同步更新
Atoms 是一种比 refs 更轻量级的机制。在事务中可以协调多个 ref 的更新,而 atoms 允许对单个值进行更新,且与其他操作无协调关系。
1.1 创建 Atoms
可以使用 atom 函数创建 atoms,其签名与 ref 非常相似:
(atom initial-state options?)
; options include:
;
:validator validate-fn
;
:meta metadata-map
例如,在音乐播放器示例中,可以将当前曲目存储在 atom 中:
(def current-track (atom "Venus, the Bringer of Peace"))
; -> #'user/current-track
1.2 获取 Atoms 的值
可以像解引用 ref 一样解引用 atom 来获取其值:
(deref current-track)
; -> "Venus, the Bringer of Peace"
@current-track
; -> "Venus, the Bringer
超级会员免费看
订阅专栏 解锁全文
30

被折叠的 条评论
为什么被折叠?



