core-async 2023-04-20

Hey team, I want to add a cleanup function of sorts, whenever a channel closes. As an example:

(defn loop-work []
  (let [ch (a/chan)]
    (a/go-loop []
      (let [i (rand-int 100)]
        (if (> i 50)
          (a/close! ch)
          (do
            (a/>! ch i)
            (recur)))))
    ch))

(defn create []
  (let [ch (loop-work)]
    ;; when ch closes, I want to do some cleanup here
    ch))

(def ch (create))
(a/go-loop
 []
  (when-let [x (a/<! ch)]
    (println x)
    (recur)))
In create, I would like to do some cleanup whenever I detect that ch has closed. --- Is there any idiomatic way to do that? Afaik I could use something like mult and have a go-loop inside create too, but I wonder if I am just thinking about this wrong

Ah, that's a great idea! Thanks @jkr.sw

You can pass a channel into loop-work rather than creating one inside, which will let to react to the go-loop ending: https://paste.rs/jiK