Skip to content

Instantly share code, notes, and snippets.

@gerritjvv
Created September 10, 2013 11:29
Show Gist options
  • Save gerritjvv/6508101 to your computer and use it in GitHub Desktop.
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…
;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)
@viperscape
Copy link

thanks for this. interesting use of complement inside the filter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment