Optimal way to iterate through core.async pipe for printing?
I am trying to dump the results of the core.async pipe to stdout.
Here's what I have (simplified example):
(use 'clojure.core.async)
(def mychan (to-chan (range 100)))
(loop []
(let [a (<!! mychan)]
(if (not (nil? a))
(do
(println a)
(recur)))))
Now I think I can replace this with a map:
(map (fn [a] (println a) a) [mychan])
But this seems to be lazy and returns no results.
I can't help but feel like my loop function is a workaround. My question is: What is the optimal way to iterate over the core.async channel for printing?
+3
source to share
1 answer
Better to use a go-loop to start the registration process in a go block:
(def c (async/chan 10))
(go-loop []
(when-let [msg (<! c)]
(println msg)
(recur)))
(async/onto-chan c (range 100))
or you can use converters on 1.7
(def prn-chan (async/chan 10 (map println)))
(async/onto-chan prn-chan (range 100))
+4
source to share