🐛 Fix problems with embed data cache

This commit is contained in:
alonso.torres 2022-05-25 17:59:26 +02:00
parent 11b2144274
commit 402212c808
2 changed files with 51 additions and 32 deletions

View file

@ -10,17 +10,34 @@
[beicon.core :as rx]))
(defonce cache (atom {}))
(defonce pending (atom {}))
(defn with-cache
[{:keys [key max-age]} observable]
(let [entry (get @cache key)
pending-entry (get @pending key)
age (when entry
(dt/diff (dt/now)
(:created-at entry)))]
(if (and (some? entry) (< age max-age))
(cond
(and (some? entry) (< age max-age))
(rx/of (:data entry))
(->> observable
(rx/tap
(fn [data]
(let [entry {:created-at (dt/now) :data data}]
(swap! cache assoc key entry))))))))
(some? pending-entry)
pending-entry
:else
(let [subject (rx/subject)]
(swap! pending assoc key subject)
(->> observable
(rx/catch #(do (rx/error! subject %)
(swap! pending dissoc key)
(rx/throw %)))
(rx/tap
(fn [data]
(let [entry {:created-at (dt/now) :data data}]
(swap! cache assoc key entry))
(rx/push! subject data)
(rx/end! subject)
(swap! pending dissoc key))))))))