Skip to content

Instantly share code, notes, and snippets.

@stoeckley
Created July 30, 2017 17:34
Show Gist options
  • Save stoeckley/9fbbca841b1e03eeea7b2ffbe3a89282 to your computer and use it in GitHub Desktop.
Save stoeckley/9fbbca841b1e03eeea7b2ffbe3a89282 to your computer and use it in GitHub Desktop.
drain a core.async chan
(defn drain
"Takes all values available on a chan then returns the number taken to the channel drain creates. Compatible with cljs too."
[c]
(go
(loop [r 0]
(alt!
(timeout 100) r
c ([v] (recur (inc r)))))))
(defn drainf
"Takes all values available on a chan then returns a vector of them, leaving the channel empty. Compatible with cljs too. Optionally takes a single function which accepts a single value and will process each drained value with this function, while also placing original value onto the vector."
[c & f]
(go
(loop [r []]
(alt!
(timeout 700) r
c ([v]
(when f ;;handling side-effects during draining
((first f) v))
(recur (conj r v)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment