Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Show notes for Apropos on January 18, 2019.
@mfikes
Copy link

mfikes commented Jan 17, 2019

Clojure/North https://clojurenorth.com (I'll be speaking, talking about ClojureScript type inference updates.)

@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