Created
January 5, 2021 05:26
-
-
Save didibus/711c6e5aed9a96cad910a68214fa7237 to your computer and use it in GitHub Desktop.
Use Clojure agents to concurrently filter out elements from a collection which requires calling a remote API to know if the element should be filtered or not.
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
(defn api-pred [e] | |
(Thread/sleep 100) | |
(even? e)) | |
(let [coll-to-process (range 1000) | |
concurrency 100 | |
agents (repeatedly concurrency #(agent []))] | |
(doseq [[i agnt] (map vector coll-to-process (cycle agents))] | |
(send-off agnt | |
#(if (api-pred i) | |
(conj % i) | |
%))) | |
(apply await agents) | |
(->> (mapv deref agents) | |
(reduce into))) | |
;; We spawn concurrency number of agents (so 100 in this example). And then we round-robin | |
;; sending them the task of calling the api-pred function for each collection item and if | |
;; true we conj the item over the batch the agent is handling. Then we wait for all of | |
;; them to be done, and we reduce over their results. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment