How to check if a channel is closed in clojure core.async?

I am trying out clojure core.async. I want to read values from a channel until it is closed. I could not find any documentation for this. I did find clojure.core.async.impl.protocols/closed? but none of the documentation or examples mentioned this.

Is it not the idiomatic way to check if a channel is closed or not? If not, what is the idiomatic way to do it?

1 Like

If you read nil from the channel then it is closed.

1 Like

You don’t normally ever need to check if a channel is closed. All the core.async functions will handle the closed case for you. So the pattern looks like:

(go-loop []
  (when-some [v (<! chan)]
    ;; do something with v
    (recur)))

For go processes, or when using threads:

(loop []
  (when-some [v (<!! chan)]
    ;; do something with v
    (recur)))
3 Likes