Skip to content

Instantly share code, notes, and snippets.

@viperscape
Last active December 28, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viperscape/7473059 to your computer and use it in GitHub Desktop.
Save viperscape/7473059 to your computer and use it in GitHub Desktop.
Quickly look at a core.async channel with only momentary blocking, pulls the data if it exists and thus alters the channel.Drain! will repeatedly call peek! until a maximum number of elements is pulled or until the channel is empty.
;;uses core.async and refers chan, >!, go, alts!! and timeout functions
(def c (chan))
(go (>! c {:msg "hi"}))
(defn peek! [ch & args]
"quickly looks at a channel for new incoming data, pulls it if it exists, quits otherwise;
returns seq if specifying max elements to pull"
(if-not (nil? args)
(let [s (remove nil? (repeatedly (first args) #(peek! ch)))] (if-not (empty? s) s nil))
(let [[m ch] (alts!! [ch (timeout 0)])] m)))
(peek! c) ;; {:msg "hi"}
(go (>! c {:msg "hi"}))
(go (>! c {:msg "hey"}))
(go (>! c {:msg "hello"}))
(go (>! c {:msg "holla"}))
(peek! c 20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment