Created
July 30, 2017 17:34
-
-
Save stoeckley/9fbbca841b1e03eeea7b2ffbe3a89282 to your computer and use it in GitHub Desktop.
drain a core.async chan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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