Skip to content

Instantly share code, notes, and snippets.

@joelash
Last active August 29, 2015 14:09
Show Gist options
  • Save joelash/abbf79b06e67ce3adb2d to your computer and use it in GitHub Desktop.
Save joelash/abbf79b06e67ce3adb2d to your computer and use it in GitHub Desktop.
(ns delay-chan
(:require [clojure.core.async :refer [>! <! put! chan timeout go alts!]))
(defonce model-chan (chan))
(defn delay-chan
"Take a channel to listen to and optional timeout. Returns a sleepy-chan
Will only publish latest message on sleepy-chan once per timeout."
[input-chan]
(let [output-chan (chan)]
(go
(loop [timeout-chan (timeout 5000) message nil]
(let [[value ch] (alts! [timeout-chan input-chan])]
(if (= input-chan ch)
(recur timeout-chan value)
(do
(when message
(>! output-chan message))
(recur (timeout 5000) nil))))))
output-chan))
(defn listen-to-changes! []
(let [sleepy-chan (delay-chan model-chan)]
(go
(while true
(try
(let [latest (<! sleepy-chan)]
(println "DO DELAYED WORK"))
(catch Exception e
(println "Catch in listen-to-changes!" e)))))))
;; Used inside of an add-watch
(defn changed-models [k r a b]
(when (not= a b)
(println "changed")
(put! model-chan :update)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment