Last active
June 9, 2022 06:05
-
-
Save henryw374/c2b7c4922fc2dc61a180f793cf9130ec to your computer and use it in GitHub Desktop.
clojure reagent interval subscription
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
(ns com.widdindustries.reagent-interval | |
"functions to create reagent reactions (ie ratoms) whose value changes | |
as an argument function is called periodically" | |
(:require [reagent.ratom :as ratom] | |
[reagent.core :as r])) | |
(defn interval-async | |
"create ratom whose value will initially be initial-state, | |
and thereafter may change as f is called with the 'state' atom every delay-ms" | |
[f delay-ms initial-state] | |
(let [state (r/atom initial-state) | |
_ (f state) | |
interval (js/setInterval (fn [] (f state)) delay-ms)] | |
(ratom/make-reaction | |
(fn [] @state) | |
:on-dispose (fn [] (js/clearInterval interval))))) | |
(defn interval-pure | |
"create ratom whose value will be the result of calling f every delay-ms" | |
[f delay-ms] | |
(interval-async | |
(fn [state] | |
(reset! state (f))) | |
delay-ms | |
(f))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment