What's the difference between pub and mult in core.async? & a sample usecase?
Asked Answered
Z

1

13

I've been using core.async for some time, but avoided pub and mult, since I can't really grasp a useful usecase from their documentation.

Specifically what's the purpose of the topic-fn and how would you use it in practice?

Or maybe you can map a theoretical explanation onto the following fictive approach. I think this could help a lot to see how it works in practice (if applicable at all?)

Fictive approach explained:

There would be several different views to represent the state. To let them act and respond to state-changes, I would like to have several channels (on an application level), which are - for example - dedicated to state-changes and user-inputs (like key presses).

Each of the views should be able to sub(scribe) ? to this application channel, so they can react independently to changes. Also each of the views should be possible to put something on the state-channel (but not the user-input-chan).

Zoography answered 20/3, 2014 at 10:50 Comment(0)
F
21

Channels in core.async are single put, single take. That is to say any message going in is given to only one taker. This doesn't work well in broadcast situations where many go blocks need a copy of each message put into a channel, then you need something else. This is what mult is useful for. Mult could probably also be called "broadcast"

Pub is then mult + multimethods. topic-fn is a function that is applied to each input item. The output of the function decides the topic of the message. The input message is then only broadcast to those subscribers who are listening to that topic.

More information is in the notes from my talk at the last Conj, available here: https://github.com/halgari/clojure-conj-2013-core.async-examples/blob/master/src/clojure_conj_talk/core.clj#L398

Fritz answered 20/3, 2014 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.