philipbohun.com

Glojure by Example: Stateful Goroutines

Another way to own state is to keep it in one loop and talk to that loop over a channel. Callers send a vector of an operation, a reply channel, and an amount. Only the loop touches balance.

(require '[clojure.core.async :as async])

(def commands (async/chan))

(async/go-loop [balance 0]
  (when-let [msg (async/<! commands)]
    (let [[op reply amount] msg]
      (case op
        :deposit (do
                   (async/>! reply (+ balance amount))
                   (recur (+ balance amount)))
        :query (do
                 (async/>! reply balance)
                 (recur balance))))))

call creates a fresh reply channel for each request, so the caller waits for its own answer.

(defn call [op amount]
  (let [reply (async/chan)]
    (async/>! commands [op reply amount])
    (async/<! reply)))

(println (call :deposit 10))
(println (call :deposit 5))
(println (call :query 0))

The balance lives in the loop, not in an atom.

$ glj stateful-goroutines.glj
10
15
15

Next example: Sorting.