Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to peek into Clojure async channels without consuming their values?

I'm trying to debug something and I'd like to see what's on the channel before consuming it.

like image 654
interstar Avatar asked Dec 02 '25 10:12

interstar


1 Answers

Only for the sake of debugging, you may use something similar to function below to observe a value on a channel without actually take!ing it (warning: this relies heavily on core.async implementation details):

(defn peek [ch]
  (if (and (.buf ch)
           (pos? (count (.buf ch))))
    (if (instance? clojure.core.async.impl.buffers.PromiseBuffer
                   (.buf ch))
      (a/<!! ch)
      (last (.buf (.buf ch))))
    (some-> ch .puts first second)))

core.async itself doesn't provide public API for peeking value from channel.

As noted by @amalloy, the function above may fail for other kinds of buffers, in particular for those that don't have buf field declared.

like image 75
OlegTheCat Avatar answered Dec 05 '25 17:12

OlegTheCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!