Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 504
rene_gr Avatar asked Mar 20 '14 10:03

rene_gr


1 Answers

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

like image 150
Timothy Baldridge Avatar answered Sep 24 '22 01:09

Timothy Baldridge