Skip to content

Instantly share code, notes, and snippets.

@bmabey

bmabey/sandbox.clj

Last active Jun 17, 2016
Embed
What would you like to do?
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