Last active
October 7, 2024 05:05
-
-
Save danielsz/7b9e4e2f718a197fc5bf3efe82d2befe to your computer and use it in GitHub Desktop.
Polling endpoint with core.async
This file contains hidden or 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
(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