Last active
August 29, 2015 14:15
-
-
Save AdamClements/33ef8d6ac9a65e9361ae to your computer and use it in GitHub Desktop.
Core async fake timeout
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
(defrecord FakeTimeout [current-time time-chans]) | |
(defn timeout-fn | |
[{:keys [current-time time-chans]}] | |
(fn [time] | |
(let [ch (async/chan)] | |
(swap! time-chans merge-with into {(+ @current-time time) #{ch}}) | |
(println time-chans) | |
ch))) | |
(defn fast-forward [{:keys [current-time time-chans]} elapsed] | |
(let [end-time (swap! current-time + elapsed) | |
affected (sort < (filter <= (keys @time-chans)))] | |
(doseq [timeindex affected] | |
(doseq [ch (get time-chans timeindex)] (async/close! ch)) | |
(swap! time-chans dissoc timeindex)))) | |
(defn fake-timeout-factory [] (->FakeTimeout (atom 0) (atom {}))) |
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
(def fakeout (fake-timeout-factory)) | |
(with-redefs [async/timeout (timeout-fn fakeout)] | |
(async/go (async/<! (async/timeout 2000)) (println "Hi"))) | |
;... Wait more than two seconds, expect no "Hi" | |
(fast-forward fakeout 3000) | |
; Expect "Hi" immediately |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment