bpereira
bpereira

Reputation: 1016

Using swap! instead of reset! in atom - clojure

Given I have this action to perform

(def structure (atom [{:id "an-id"} {:id "another-id"}]))
(def job {:type "some-job"})

(reset! structure (map #(if (= "an-id" (:id %)) (update-in % [:performed-jobs] (fnil conj []) job) %) @structure))

next structure:
[{:id "an-id" :performed-jobs [{:type "some-job"}]} {:id "another-id"}]

How can I use swap! to change a single occurrence in my structure instead of resetting it all?

Upvotes: 1

Views: 349

Answers (1)

Michiel Borkent
Michiel Borkent

Reputation: 34800

  1. Replace reset! by swap! by giving it a function that takes the old value of the atom and returns a new value to store in the atom.
  2. Replace dereferencing of the atom with the function's argument, the old value.

    (swap! structure
      (fn [old]
        (map #(if (= "an-id" (:id %))
                (update-in % [:performed-jobs]
                           (fnil conj []) job) %)
              old)))
    

Upvotes: 1

Related Questions