Skip to content

Instantly share code, notes, and snippets.

@henryw374
Last active June 9, 2022 06:05
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 henryw374/c2b7c4922fc2dc61a180f793cf9130ec to your computer and use it in GitHub Desktop.
Save henryw374/c2b7c4922fc2dc61a180f793cf9130ec to your computer and use it in GitHub Desktop.
clojure reagent interval subscription
(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