Created
September 10, 2013 11:29
-
-
Save gerritjvv/6508101 to your computer and use it in GitHub Desktop.
Connection as a Sequence sleep retry on nil Lets say you have a connection that you want to stream results from. The connection can also return zero data in which case you would want to sleep and retry until data is available. A complicated solution would be to do this with a loop recur but a more elegant pattern can be created using map and fil…
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
;for testing purposes lets simulate a connection that will return nil or 1 | |
(defn connect-and-get [] (rand-nth [nil 1 1 1 nil 1 nil 1 nil])) | |
(def select-data (repeatedly connect-and-get)) | |
(defn sleep-while-nil [ts s] | |
(filter (complement nil?) (map (fn [x] (if-not x (Thread/sleep ts)) x) s))) | |
(take 10 (sleep-while-nil 100 select-data)) | |
;;(1 1 1 1 1 1 1 1 1 1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for this. interesting use of complement inside the filter