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
If the Observer pattern is essentially about publishers and subscribers then Clojure has a couple of functions that you could use:
The add-watch function takes three arguments: a reference, a watch function key, and a watch function that is called when the reference changes state.
Clearly, because of the changes in mutable state, this is not purely functional (as you clearly requested), but add-watcher
will give you a way to react to events, if that's the effect you were seeking, like so:
(def number-cats (ref 3))
(defn updated-cat-count [k r o n]
;; Takes a function key, reference, old value and new value
(println (str "Number of cats was " o))
(println (str "Number of cats is now " n)))
(add-watch number-cats :cat-count-watcher updated-cat-count)
(dosync (alter number-cats inc))
Output:
Number of cats was 3
Number of cats is now 4
4