Skip to content

Instantly share code, notes, and snippets.

@pbaille
Last active December 6, 2016 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbaille/6616353731efe5bfa00869c6338b03c7 to your computer and use it in GitHub Desktop.
Save pbaille/6616353731efe5bfa00869c6338b03c7 to your computer and use it in GitHub Desktop.
reactive wrapper
(defn rwrap [build deps-map]
(let [this (atom (build))
deps (keys deps-map)
propagating (atom nil)]
(add-watch this
:build
(fn [_ _ _ n]
(when-not @propagating
(reset! propagating true)
(doseq [[dep upd] deps-map]
(swap! dep (or upd (fn [x _] x)) n))
(reset! propagating false))))
(doseq [r deps]
(add-watch r
(keyword (gensym))
(fn [_ _ _ _]
(when-not @propagating
(reset! propagating true)
(reset! this (build))
(reset! propagating false)))))
this))
(def p println)
(defn rwrap-debug [build deps-map]
(let [this (atom (build))
deps (keys deps-map)
propagating (atom nil)]
(add-watch this
:build
(fn [_ _ _ n]
(if @propagating
(p "propagation form this stopped")
(do (reset! propagating true)
(doseq [[dep upd] deps-map]
(p (str "propagate this change to " (pr-str dep)))
(swap! dep (or upd (fn [x _] x)) n))
(p "done propagating")
(reset! propagating false)))))
(doseq [r deps]
(add-watch r
(keyword (gensym))
(fn [_ _ _ _]
(if @propagating
(p "propagation to this stopped")
(do
(reset! propagating true)
(p "propagate to this")
(reset! this (build))
(p "done propagating")
(reset! propagating false))))))
this))
(comment
(let [dep1 (atom 10)
dep2 (atom 0)
this (rwrap-debug
(fn [] {:a @dep1 :b @dep2})
{dep1 (fn [_ v] (:a v))
dep2 (fn [_ v] (:b v))})]
(p "<> (swap! this update :a inc) <>")
(swap! this update :a inc)
(p "<> (swap! dep1 inc) <>")
(swap! dep1 inc)
(p "<> (swap! dep2 dec) <>")
(swap! dep2 dec)
(assert (and
(= @dep1 12)
(= @dep2 -1)
(= @this {:a 12 :b -1})))
nil))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment