Fork me on GitHub
#core-async
<
2022-02-11
>
Neil Barrett14:02:25

Hi everyone. Here is a modified example from https://clojuredocs.org/clojure.core.async/pub.

(def src (chan 1))
(def publisher (pub src :topic))

(def alice (chan 1))
(def bob (chan 1))
(def clyde (chan 1))

(sub publisher :celebrity-gossip alice)
(sub publisher :space-x bob)
(sub publisher :space-x clyde)

(def a-alice (atom []))
(def a-bob (atom []))
(def a-clyde (atom []))

(go-loop [heard (<! alice)] (reset! a-alice conj (str "alice heard: " heard)))
(go-loop [heard (<! bob)] (reset! a-bob (str "bob heard: " heard)))
(go-loop [heard (<! clyde)] (reset! a-clyde (str "clyde heard: " heard)))

(put! src {:topic :celebrity-gossip :data "omg she's prego!"})
(put! src {:topic :space-x :data "omg we're landing!"})

Neil Barrett14:02:55

Why does @a-alice return []?

danboykis14:02:43

@neil.barrett16 i haven't looked at this too carefully yet, but do you mean swap! instead of reset! for the atoms?

✔️ 1
danboykis14:02:29

can you rerun it and see if the result is still wrong?

Neil Barrett14:02:40

Perfect! Silly of me. Thanks a lot.

👍 1
Neil Barrett14:02:36

Of course! I used conj with reset!.

Neil Barrett14:02:04

Is there any way to get println to work in a go or go-loop in Clojupyter? Does it work in a standard repl?

ghadi15:02:33

printing in background threads works with a standard REPL, but not always with nREPL-based things (Not sure what Clojupyter uses) standard REPL meaning clojure.main

ghadi15:02:06

another alternative to printing in background threads is passing things a log channel

ghadi15:02:16

data > dead text

Neil Barrett15:02:24

Great! I'll try that.

Neil Barrett15:02:53

How would I print from the log channel? Won't it have to be in a go-loop?

Neil Barrett15:02:23

Or would I write to a file?

Neil Barrett15:02:26

This works with Clojupyter:

(def src (chan 1))
(def publisher (pub src :topic))

(def alice (chan 1))
(def bob (chan 1))
(def clyde (chan 1))

(sub publisher :celebrity-gossip alice)
(sub publisher :space-x bob)
(sub publisher :space-x clyde)

(def log-atom (atom nil))
(add-watch log-atom :key (fn [_ _ _ ns] (println ns)))

(defn log [msg]
    (reset! log-atom msg))

(go-loop [] 
    (when-let [heard (<! alice)] 
        (log (str "alice heard: " heard))
        (recur)))
(go-loop [] 
    (when-let [heard (<! bob)] 
        (log (str "bob heard: " heard))
        (recur)))
(go-loop [] 
    (when-let [heard (<! clyde)] 
        (log (str "clyde heard: " heard))
        (recur)))

(put! src {:topic :celebrity-gossip :data "omg she's prego!"})
(put! src {:topic :space-x :data "omg we're landing!"})
(put! src {:topic :space-x :data "omg we're launching!"})
(close! src)