Codebase list core-async-clojure / 9912cca4-edd0-40b2-8709-b362893ac6b1/main examples / ex-alts.clj
9912cca4-edd0-40b2-8709-b362893ac6b1/main

Tree @9912cca4-edd0-40b2-8709-b362893ac6b1/main (Download .tar.gz)

ex-alts.clj @9912cca4-edd0-40b2-8709-b362893ac6b1/mainraw · history · blame

(require '[clojure.core.async :as async :refer [<! >! <!! >!! timeout chan alt! alts!! go]])

(defn fan-in [ins]
  (let [c (chan)]
   (future (while true
             (let [[x] (alts!! ins)]
               (>!! c x))))
   c))

(defn fan-out [in cs-or-n]
  (let [cs (if (number? cs-or-n)
             (repeatedly cs-or-n chan)
             cs-or-n)]
   (future (while true
             (let [x (<!! in)
                   outs (map #(vector % x) cs)]
               (alts!! outs))))
   cs))

(let [cout (chan)
      cin (fan-in (fan-out cout (repeatedly 3 chan)))]
  (dotimes [n 10]
    (>!! cout n)
    (prn (<!! cin))))