Skip to content

Instantly share code, notes, and snippets.

@bmabey
Last active June 17, 2016 19:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmabey/6023231 to your computer and use it in GitHub Desktop.
Save bmabey/6023231 to your computer and use it in GitHub Desktop.
macros to stop a loop and timeouts in core.async
(require '[clojure.core.async :as async :refer :all])
(defmacro sleep
([ms stop-channel]
`(alts! [(timeout ~ms) ~stop-channel]))
([ms]
`(<! (timeout ~ms))))
(defmacro go-loop [bindings & body]
(let [stop (first bindings)]
`(let [~stop (chan)]
(go (while (alt! ~stop false :default :keep-going)
~@body))
~stop)))
(defn hello-world [x]
(go-loop [stop-timeout]
(println "Hello World!")
(sleep x stop-timeout)
(println "I'm done sleeping, going to recur now...")))
;; user> (def q (hello-world 10000))
;; #'user/q
;; Hello World!
;; I'm done sleeping, going to recur now...
;; Hello World!
;; user> (close! q)
;; I'm done sleeping, going to recur now...
;; nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment