26 April 2020

Websocket Subscriptions in Fulcro

How do I keep my clients up to date?

At this point it's pretty easy!

That's right this turned out to be pretty straightforward =)...

If you're not sure how to setup websockets in Fulcro, we've covered it before here.

Now for a quick dash through this, fundamentally we just need to setup two functions, one to interact with the server-side and one to capture whatever we sent from the client-side.

Let's tackle the server-side first.

In app/server_components/websockets.clj, we can define a broadcast function:

(ns app.server-components.websockets
  (:require ...
            [com.fulcrologic.fulcro.networking.websocket-protocols :refer [push]] ;; Primarily we're just pulling in this
            ...))
...

(defn broadcast! [topic data]
  (let [uids (:any @(:connected-uids websockets))]
    (doseq [uid uids]
      (push websockets uid topic data))))

I've just done a broadcast function, because that's straightforward =)...

Then in app/application.cljs we define a push-handler function and pass it into fulcro-websocket-remote:

(defn push-handler [{:keys [topic msg]}]
  (println :push-handler topic msg))

(defonce SPA
  (app/fulcro-app
    {:remotes {:remote (net/fulcro-http-remote
                         {:url "/api"
                          :request-middleware secured-request-middleware})
               :ws-remote (fws/fulcro-websocket-remote {:push-handler push-handler})}})) ;; In it goes =)...

Similarly your push handler can be arbitrarily complex.

Now if you just call in app.server-components.websockets:

(broadcast! :test! {:a 1 :b "b"})

You should see the text below appear in your js console:

:push-handler :test! {:a 1 :b "b"}

And we're done! Told you that would be quick!

PS: Example of where we started from

If you're having issues, Here's where we began from.

Tags: beginner fulcro websockets subscriptions