Skip to content

Instantly share code, notes, and snippets.

@tobias
Created December 9, 2013 22:30
Show Gist options
  • Select an option

  • Save tobias/7882167 to your computer and use it in GitHub Desktop.

Select an option

Save tobias/7882167 to your computer and use it in GitHub Desktop.
(defn ^:internal ^:no-doc delayed
"Creates an timeout-derefable delay around any function taking a timeout"
[f]
(let [val (atom ::unrealized)
realized? #(not= ::unrealized @val)
rcv (fn [timeout] (reset! val (f timeout)))]
(proxy [clojure.lang.Delay clojure.lang.IBlockingDeref] [nil]
(deref
([]
(if (realized?) @val (rcv 0)))
([timeout-ms timeout-val]
(if (realized?)
@val
(let [r (rcv timeout-ms)]
(if (nil? r) timeout-val r)))))
(isRealized []
(or (realized?)
(not (nil? (rcv -1))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment