Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Converting callbacks to async channels
(ns kanalid.core
; (:require-macros [cljs.core.async.macros :refer [go go-loop]])
(:require [cljs.core.async :refer [go <! put!] :as async]
["events" :as EventEmitter]))
(def global-emitter (new EventEmitter))
(defn emit [event data]
(.emit global-emitter event data))
(defn subscribe
"Returns JavaScript EventEmitter that emits strings"
[emitter event-name callback]
(.addListener emitter event-name callback)
(defn subscribe->channel [emitter event-name]
(let [channel (async/chan)]
(subscribe emitter event-name #(put! channel %))
(defn example []
(let [channel (async/chan)
emitter (new EventEmitter)
event-name :happening]
(.addListener emitter event-name #(put! channel %))
(.emit emitter event-name 42)
(.emit emitter event-name "Wadiis")
(async/go-loop []
(let [val-from-channel (<! channel)]
(println "Got value from ze channel: " val-from-channel)
(println "Done in let"))
(println "Done in example"))
(defn example-two []
(let [jobs-channel (subscribe->channel global-emitter :create-job)]
(emit :create-job 42)
(println "Got a new value: " (<! jobs-channel))
(defn main []
(println "Hello world!")
;; shadow-cljs configuration
{:server {:target :node-script
:main kanalid.core/main
:output-to "out/kanalid.js"}}}
  1. Watch the build shadow-cljs watch server
  2. Run the code node out/kanalid.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment