(mult ch)
Creates and returns a mult(iple) of the supplied channel. Channels
containing copies of the channel can be created with 'tap', and
detached with 'untap'.
Each item is distributed to all taps in parallel and synchronously,
i.e. each tap must accept before the next item is distributed. Use
buffering/windowing to prevent slow taps from holding up the mult.
Items received when there are no taps get dropped.
If a tap puts to a closed channel, it will be removed from the mult.
Source
(defn
mult
"Creates and returns a mult(iple) of the supplied channel. Channels\n containing copies of the channel can be created with 'tap', and\n detached with 'untap'.\n\n Each item is distributed to all taps in parallel and synchronously,\n i.e. each tap must accept before the next item is distributed. Use\n buffering/windowing to prevent slow taps from holding up the mult.\n\n Items received when there are no taps get dropped.\n\n If a tap puts to a closed channel, it will be removed from the mult."
[ch]
(let
[cs
(atom {})
m
(reify
Mux
(muxch* [_] ch)
Mult
(tap* [_ ch close?] (swap! cs assoc ch close?) nil)
(untap* [_ ch] (swap! cs dissoc ch) nil)
(untap-all* [_] (reset! cs {}) nil))
dchan
(chan 1)
dctr
(atom nil)
done
(fn [_] (when (zero? (swap! dctr dec)) (put! dchan true)))]
(go-loop
[]
(let
[val (<! ch)]
(if
(nil? val)
(doseq [[c close?] @cs] (when close? (close! c)))
(let
[chs (keys @cs)]
(reset! dctr (count chs))
(doseq
[c chs]
(when-not (put! c val done) (done nil) (untap* m c)))
(when (seq chs) (<! dchan))
(recur)))))
m))