Skip to content

Instantly share code, notes, and snippets.

@samedhi
Created July 14, 2019 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samedhi/0e8f5e565877742a5d2649a98b12f715 to your computer and use it in GitHub Desktop.
Save samedhi/0e8f5e565877742a5d2649a98b12f715 to your computer and use it in GitHub Desktop.
A buffer that will take a side effect when the channel containing it is closed.
(deftype FinalizingBuffer [buf n opts]
cljs.core.async.impl.protocols/Buffer
(full? [this]
(== (.-length buf) n))
(remove! [this]
(.pop buf))
(add!* [this itm]
(.unbounded-unshift buf itm)
this)
(close-buf! [this]
(some-> opts :on-close (apply [this])))
cljs.core/ICounted
(-count [this]
(.-length buf)))
(defn finalizing-buffer
([n] (finalizing-buffer n {}))
([n opts]
(FinalizingBuffer.
(cljs.core.async.impl.buffers/ring-buffer n)
n
opts)))
(def c1 (async/chan
(finalizing-buffer
1
{:on-close #(js/console.log "Deregister event listener put!'ing values in c1")})))
(async/go-loop []
(when-let [v (async/<! c1)]
(js/console.log "v1 ->" v)
(recur)))
(async/go
(async/put! c1 "test1")
(async/<! (async/timeout 100))
(async/put! c1 "test2")
(async/<! (async/timeout 100))
(async/close! c1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment