M Smith
M Smith

Reputation: 2028

Is there a single publish-subscribe that will work in both clojure and clojurescript

I am attempting to write a game, Crossfire, that will run in both clojure and ClojureScript and I need a publish-subscribe mechanism that will work in both. I have seen lamina and Shoreleave but both are dependent on their respective environments.

I need to have an event system where a subscriber can wait for a message.

Upvotes: 4

Views: 429

Answers (1)

levand
levand

Reputation: 8500

Update:

This question was asked and answered before core.async was released. core.async is designed to solve precisely this problem, you should definitely use it for all projects going forward.

Original answer:

It's not truly asynchronous, but I have grown quite fond of using atoms and watchers for this. Very simple but highly flexible model, and built in to both languages.

An extremely simple example:

(def my-channel (atom nil))

;; subscribe
(add-watch my-channel :watcher1
  (fn [_ _ _ message]
    (js/alert (str "Received message: " message))))

;; publish
(reset! my-channel "my-message")

;; unsubscribe
(remove-watch my-channel :watcher1)

The beauty of this approach is that the state of the atom can be any object. Here, I'm simply resetting the state of the atom the message, but you could also have the state of the atom be the full history of messages, or the last 5 messages, or a state machine representing your entire system, or whatever you want.

Upvotes: 4

Related Questions