Liking cljdoc? Tell your friends :D


Clojars Project

Simple asynchronous in-process event broker for Clojure.


Latest version

Available from Clojars.


Start a broker and publish a message:

(require '[ :as broker])

(def broker (broker/start))

(broker/publish! broker [:broker-started])

By default, messages are expected to be vectors, with the first element being a keyword to represent the type of message. This is the same structure as used by libraries such as re-frame and sente.

The broker uses the message type as a topic, and allows subscribers to select which messages they are interested in. To subscribe to messages, use subscribe:

(defn notify-hello [[_ name]]]
  (println "Hello," (:name name)))

(broker/subscribe broker :hello notify-hello)

(broker/publish! broker [:hello "Broker!"])
; Hello, Broker!

(broker/subscribe broker #(println "Observed:" %))

(broker/publish! broker [:hello "All!"])
; Observed: [:hello "All!"]
; Hello, All!

(broker/publish! broker [:hi "what's up?"])
; Observed: [:hi "what's up?"]

To customize the message format, you can supply a :topic-fn:

;; Dispatch on the :msg/topic key instead:
(def broker (broker/start {:topic-fn :msg/topic}))

(broker/publish! broker {:msg/topic :my.domain/widget-created})

Under the hood, broker uses core.async. Instead of functions, you can also subscribe with async channels:

(require '[clojure.core.async :as async])

(def ch (async/chan))

(broker/subscribe broker :hi ch)

You can stop receiving messages with unsubscribe and release all subscriptions with unsubscribe-all:

;; Unsubscribe a channel from a topic:
(broker/unsubscribe broker :hi ch)

;; Unsubscribe a function from all topics:
(broker/unsubscribe broker notify-hello)

;; Remove all subscriptions:
(broker/unsubscribe-all broker)

You can stop the router with stop!:

(broker/stop! broker)

;; This has no effect:
(broker/publish! broker [:more]) ; => false


Distributed under the MIT License.
Copyright © 2022 Ferdinand Beyer

Can you improve this documentation?Edit on GitHub

cljdoc is a website building & hosting documentation for Clojure/Script libraries

× close