Skip to content

Instantly share code, notes, and snippets.

@gerritjvv
Created December 31, 2013 16:58
Show Gist options
  • Save gerritjvv/8199545 to your computer and use it in GitHub Desktop.
Save gerritjvv/8199545 to your computer and use it in GitHub Desktop.
Simple thing to do, but requires repeated typing. The only thing it does is move from channel-a to channel-b. This function is implemented in https://github.com/gerritjvv/fun-utils
(require '[clojure.core.async :refer [chan go >! <! >!! <!!]])
(require '[clojure.core.async :as async])
(defn chan-bridge
([ch-source map-f ch-target]
"map map-f onto ch-source and copy the result to ch-target"
(chan-bridge (async/map map-f [ch-source]) ch-target))
([ch-source ch-target]
"in a loop read from ch-source and write to ch-target
this function returns inmediately and returns the ch-target"
(go
(while (not (Thread/interrupted))
(if-let [v (<! ch-source)]
(>! ch-target v))))
ch-target))
;; test
(let [ch1 (chan 10)
ch2 (chan-bridge ch1 (chan 10))]
(doseq [i (range 5)] (>!! ch1 i))
(prn (reduce + (repeatedly 5 #(<!! ch2)))))
;; 10
(let [ch1 (chan 10)
ch2 (chan-bridge ch1 inc (chan 10))]
(doseq [i (range 5)] (>!! ch1 i))
(prn (reduce + (repeatedly 5 #(<!! ch2)))))
;; 15
@thegeez
Copy link

thegeez commented Jan 1, 2014

core.async has the pipe function for this:
http://clojure.github.io/core.async/#clojure.core.async/pipe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment