Let\'s say I want to implement an event bus using a OO programming language. I could do this (pseudocode):
class EventBus
listeners = []
public registe
I'd suggest creating a ref which contains a set of listeners, each of which is a function that acts on an event.
Something like:
(def listeners (ref #{}))
(defn register-listener [listener]
(dosync
(alter listeners conj listener)))
(defn unregister-listener [listener]
(dosync
(alter listeners disj listener)))
(defn fire-event [event]
(doall
(map #(% event) @listeners)))
Note that you are using mutable state here, but that is OK because the problem you are trying to solve explicitly requires state in terms of keeping track of a set of listeners.
Note thanks to C.A.McCann's comment: I'm using a "ref" which stores the set of active listeners which has the nice bonus property that the solution is safe for concurrency. All updates take place protected by the STM transaction within the (dosync ....) construct. In this case it's possibly overkill (e.g. an atom would also do the trick) but this might come in handy in more complex situations, e.g. when you are registering/unregistering a complex set of listeners and want the update to take place in a single, thread-safe transation.