(pipe from to) (pipe from to close?)
Takes elements from the from channel and supplies them to the to channel. By default, the to channel will be closed when the from channel closes, but can be determined by the close? parameter. Will stop consuming the from channel if the to channel closes
user=> (def cx (chan 1))
#'user/cx
user=> (def cy (chan 1))
#'user/cy
user=> (pipe cx cy)
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@5064227c>
user=> (put! cx "Going into CX")
true
user=> (<!! cy)
"Going into CX"
user> (def ch-1 (async/chan 10))
#'user/ch-1
user> (def ch-2 (async/chan 10))
#'user/ch-2
;; start a thread that takes from channel 1, sleeping after each take
user> (async/thread
(loop []
(when-let [v (async/<!! ch-1)]
(println "ch-1 taker got " v)
(Thread/sleep 1000)
(recur))))
#object[clojure.core.async.impl.channels.ManyToManyChannel ...]
;; start a thread that takes from channel 2 that does not sleep
user> (async/thread
(loop []
(when-let [v (async/<!! ch-2)]
(println "ch-2 taker got " v)
(recur))))
#object[clojure.core.async.impl.channels.ManyToManyChannel ...]
;; create a pipe from ch-1 to ch-2
user> (async/pipe ch-1 ch-2)
#object[clojure.core.async.impl.channels.ManyToManyChannel ...]
;; lets try to add a new listener to channel 1.
user> (async/thread
(loop []
(when-let [v (async/<!! ch-1)]
(println "second ch-1 taker got " v)
(Thread/sleep 1000)
(recur))))
#object[clojure.core.async.impl.channels.ManyToManyChannel ...]
;; put onto ch-1 and sleep after each put... we are interested in how the
;; pipe works...
user> (async/thread
(doseq [x (range 10)]
(async/>!! ch-1 x)
(Thread/sleep 500)))
#object[clojure.core.async.impl.channels.ManyToManyChannel ...]
ch-1 taker got 0
ch-2 taker got 1
second ch-1 taker got 2
ch-2 taker got 3
ch-1 taker got 4
ch-2 taker got 5
second ch-1 taker got 6
ch-2 taker got 7
ch-1 taker got 8
ch-2 taker got 9
;; so a pipe is just a listener that tries to take from the from channel
;; and put onto the to channel, a pipe does dot restrict the ability to
;; *take* from the *from* channel.