aav
aav

Reputation: 2489

messages publish before subscribe in core.async

In the following example I can see, that published messages arrive to the subscribed channel, although, they are published before subscription is made.

(let [in (async/chan)
      out (async/chan)
      pub (async/pub in :key)]

  (async/go
    (>! in {:id 1 :key :k1})  
    (>! in {:id 2 :key :k1})  
    (>! in {:id 3 :key :k1}))

    (async/sub pub :k1 out)

    (async/go-loop []
      (println (<! out)) 
      (recur)))

Is this expected behavior? As far as I can see in the documentation, it clearly states:

Items received when there are no matching subs get dropped.

I get same results in both Clojure and ClojureScript.

Added: with mult/tap I see similar behavior

Upvotes: 2

Views: 233

Answers (1)

Diego Basch
Diego Basch

Reputation: 13079

You don't know that the messages are published before the subscription is made. Because go is asynchronous, it's very possible that the subscription happens before the first message has been put into the channel. It's a race condition, really.

Try putting a (Thread/sleep [some value]) before the suscription and see what happens.

Upvotes: 2

Related Questions