Skip to content

Instantly share code, notes, and snippets.

@naiquevin
Created January 8, 2015 18:10
Show Gist options
  • Save naiquevin/6b78186176e86c0a15e3 to your computer and use it in GitHub Desktop.
Save naiquevin/6b78186176e86c0a15e3 to your computer and use it in GitHub Desktop.
clojure core.async - consume until some timeout
(defn consume-until-timeout
[ms ch f init & args]
(let [tmt (timeout ms)]
(go (loop [ret init]
(if-let [v (first (alts! [ch tmt]))]
(recur (apply f ret [v]))
ret)))))
(comment
(let [c (chan)]
(doseq [i (range 1 7)]
(go (>! c (do
(Thread/sleep (* i 1000))
i))))
(<!! (consume-until-timeout 3000 c conj []))))
(comment
(let [c (chan)]
(doseq [i (range 1 7)]
(go (>! c (do
(Thread/sleep (* i 1000))
i))))
(consume-until-timeout 6100 c prn [])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment