Fork me on GitHub
#core-async
<
2015-12-04
>
danielgrosse11:12:15

When I define a channel and use it directly, how can I close the channel later?

(let [view-chan (chan 1)]

  (go-loop []
    (let [response (<! view-chan)]
        (println response)
        )
      (recur))
    )

karlis11:12:31

with clojure.core.async/close!

d-t-w11:12:51

(let [view-chan (async/chan 5)]
  (async/put! view-chan "a")
  (async/put! view-chan "b")
  (async/put! view-chan "c")

  (async/go-loop []
    (when-let [response (async/<! view-chan)]
      (println response))
    (recur))
  
  (async/close! view-chan)
  view-chan)

d-t-w11:12:35

when reading from a channel in a loop, you should presume the channel will return nil at some point (when some other process closes it and the channel is exhausted), and loop no more.

codemartin17:12:56

What is the best explanation of the alts! function you've seen?

ghadi17:12:21

think of it as choosing exactly one of N possible futures

erik_price17:12:22

I don’t think I’ve ever seen an explanation other than the docs, but I think of alts! as kind of like a cond where the clauses are the channels’ next value, and the conditions are whichever channel sends that value “first”.

erik_price17:12:00

(Scare quotes since the notion of order in the context of multiple threads is kind of ambiguous)

Alex Miller (Clojure team)18:12:02

I think of it as alt! + cond

erik_price18:12:28

I learned alt! much later than alts! (and, initially, found it harder to get an intuition for)

ghadi18:12:09

alexmiller: you got it backwards

ghadi18:12:27

alt! == alts! + cond

Alex Miller (Clojure team)18:12:45

I don't love the similarity of those names

ghadi18:12:55

I think codemartin is looking for just the intuition of what the operation means

Alex Miller (Clojure team)18:12:15

I liked your first answer too

ghadi18:12:39

N things can possibly happen, but you only have to deal with one of them happening, and the operation tells you exactly which happened. Handling that is up to you