Skip to content

Instantly share code, notes, and snippets.

@apropos-cast
Last active January 18, 2019 05:03
Show Gist options
  • Save apropos-cast/abf8b64452ae0ae56cafa333c1eaf4e8 to your computer and use it in GitHub Desktop.
Save apropos-cast/abf8b64452ae0ae56cafa333c1eaf4e8 to your computer and use it in GitHub Desktop.
Show notes for Apropos on January 18, 2019.
@apropos-cast
Copy link
Author

apropos-cast commented Jan 17, 2019

Solution 1

(def db (atom {}))

(add-watch db ::saver (fn [_ _ old new]
                        (spit "dbsave.edn" (pr-str new))))

(defn read-db []
  (clojure.edn/read-string (slurp "dbsave.edn")))

(defn restore-db []
  (reset! db (read-db)))

@apropos-cast
Copy link
Author

apropos-cast commented Jan 17, 2019

Solution 2

We wanted the writes to be thread-safe.

(def db (atom {}))

(def die? false)

(def t (doto (Thread. (fn []
                        (loop [old-state @db]
                          (when (not die?)
                            (Thread/sleep 1000)
                            (let [new-state @db]
                              (when (not= old-state new-state)
                                (spit "dbsave.edn" (pr-str new-state)))
                              (recur new-state))))))
         (.start)))

(defn read-db []
  (clojure.edn/read-string (slurp "dbsave.edn")))

(defn restore-db []
  (reset! db (read-db)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment