Skip to content

Instantly share code, notes, and snippets.

@danielsz
Last active November 19, 2023 03:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielsz/7b9e4e2f718a197fc5bf3efe82d2befe to your computer and use it in GitHub Desktop.
Save danielsz/7b9e4e2f718a197fc5bf3efe82d2befe to your computer and use it in GitHub Desktop.
Polling endpoint with core.async
(ns clojure.polling
(:require [clj-http.client :as client]
[clojure.core.async :as async :refer [>!! timeout <! go-loop]]
[cheshire.core :as json]
[clojure.tools.logging :as log]))
(defn client
([endpoint]
(client/get endpoint))
([endpoint c e]
(client/get endpoint {:async true}
(fn [response] (>!! c (:body response)))
(fn [exception] (>!! e (.getMessage exception))))))
(defn poll [endpoint c e]
(go-loop []
(client endpoint c e)
(<! (timeout 1000))
(recur)))
(defn read-data [c]
(go-loop []
(let [s (<! c)]
(if (empty? s)
(recur)
(let [data (json/parse-string s true)]
(log/info data)
(recur))))))
(defn read-errors [e]
(go-loop []
(let [error (<! e)]
(log/fatal error)
(recur))))
(defn polling [endpoint]
(let [c (async/chan)
e (async/chan)]
(read-data c)
(read-errors e)
(poll endpoint c e)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment