How to update state in a webapp

110 views
Skip to first unread message

babysnakes

unread,
May 28, 2016, 2:16:32 PM5/28/16
to Clojure
Hey all,

I don't have a lot of experience with clojure but I did write a few small services in clojure. Until now the state of the services I wrote were static so I constructed a system map (more or less following Stuart Sierra's reloaded workflow - without using the component framework) and injected it to the various handlers via middleware closure. This works great when the state is static. Now I have to write a small service where the state should be updated (I have to periodically pull new configurations). The first place I can think of to put this state is in a global atom, but I was wondering if there's a pattern that allows me to dynamically update global state without using global atom.

Thanks in advance

Haim

Brian Platz

unread,
May 29, 2016, 7:57:56 AM5/29/16
to Clojure
In a web-app you probably want the thread safety an atom provides, so it would be a good choice.

You can include a reference to your atom in your system config if you want to retain the reloaded-like / dependency injection pattern:

(def changing-config (atom {}))

;; system-map
(def sys-map
 {:a "a"
  :b 42
  :c changing-config})

(defn my-handler
 [handler sys-map]
 (fn [req] {:status 200 :body @(:c sys-map)}))

babysnakes

unread,
May 29, 2016, 8:10:03 AM5/29/16
to Clojure
Thanks Brian, nice idea :)

I also added load/save functionality from the atom when reloading the environment in development.
Reply all
Reply to author
Forward
0 new messages