Last active
June 17, 2016 19:36
-
-
Save bmabey/6023231 to your computer and use it in GitHub Desktop.
macros to stop a loop and timeouts in core.async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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