(swap! a f)
(swap! a f x)
(swap! a f x y)
(swap! a f x y & more)
Atomically swaps the value of atom to be:
(apply f current-value-of-atom args). Note that f may be called
multiple times, and thus should be free of side effects. Returns
the value that was swapped in.
Example
Atomically swap the value in a vector-atom
(swap! (atom [:lisp]) conj :scheme :clojure)
Atomically swap a value in a map-atom
(let [map-atom (atom {:a "A", :b [4 2]})] (swap! map-atom assoc :a "B"))
Atomically map a function over a seq-value in a map-atom
(let
[map-atom (atom {:a "A", :b [5 3]})]
(swap! map-atom update :b (partial mapv dec)))
Atomically apply a function to a value in a map-atom
(let [map-atom (atom {:a "A", :c 41})] (swap! map-atom update :c inc))
Atomically update multiple key-values in one swap
(let
[map-atom
(atom {:a "A", :b [3 1], :c 43})
update-multiple-kvs
(fn
[m k1 f1 k2 f2]
(let
[m1 (assoc m k1 (f1 (k1 m))) m2 (assoc m1 k2 (f2 (k2 m1)))]
m2))
add-bcd
(fn [a-string] (str a-string "BCD"))
inc-vec
(fn [v] (mapv inc v))]
(swap! map-atom update-multiple-kvs :a add-bcd :b inc-vec))
Source
(defn
swap!
"Atomically swaps the value of atom to be:\n (apply f current-value-of-atom args). Note that f may be called\n multiple times, and thus should be free of side effects. Returns\n the value that was swapped in."
([a f]
(if (instance? Atom a) (reset! a (f (.-state a))) (-swap! a f)))
([a f x]
(if (instance? Atom a) (reset! a (f (.-state a) x)) (-swap! a f x)))
([a f x y]
(if
(instance? Atom a)
(reset! a (f (.-state a) x y))
(-swap! a f x y)))
([a f x y & more]
(if
(instance? Atom a)
(reset! a (apply f (.-state a) x y more))
(-swap! a f x y more))))