Skip to content

Instantly share code, notes, and snippets.

@mfikes
Last active March 7, 2018 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfikes/0c8cf0630b3c86dea5e7423046745b79 to your computer and use it in GitHub Desktop.
Save mfikes/0c8cf0630b3c86dea5e7423046745b79 to your computer and use it in GitHub Desktop.
(defn connection
"Promise to return a connection when one is available. If a
connection is not available, store the promise in server/state."
[]
(let [p (promise)
{:keys [deliver-conn]} (swap! state (fn [{:keys [connection] :as the-state}]
(if (and connection (not (.isClosed connection)))
(assoc the-state :connection nil
:deliver-conn connection)
(do
(when (:promised-conn the-state)
(println "OVERWRITE :promised-con"))
(assoc the-state :promised-conn p
:deliver-conn nil)))))]
(when deliver-conn
(deliver p deliver-conn))
p))
(defn set-connection
"Given a new available connection, either use it to deliver the
connection which was promised or store the connection for later
use."
[conn]
(let [{:keys [deliver-prom]} (swap! state (fn [{:keys [promised-conn] :as the-state}]
(if promised-conn
(assoc the-state :promised-conn nil
:deliver-prom promised-conn)
(do
(when (:connection the-state)
(println "OVERWRITE :connection"))
(assoc the-state :connection conn
:deliver-prom nil)))))]
(when deliver-prom
(deliver deliver-prom conn))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment