More work on monitor

This commit is contained in:
Dan Holmsand 2015-09-13 19:01:58 +02:00
parent ee72c60d3a
commit aaf1d56edb
1 changed files with 26 additions and 10 deletions

View File

@ -109,31 +109,47 @@
(defonce cached-reactions {}) (defonce cached-reactions {})
(defn- cached-reaction [obj key f] (defn- cached-reaction [f key obj]
(if-some [r (get cached-reactions [key])] (if-some [r (get cached-reactions key)]
r (-deref r)
(if (some? *ratom-context*) (if (some? *ratom-context*)
(let [r (make-reaction (let [r (make-reaction
f :on-dispose #(set! cached-reactions f :on-dispose (fn []
(dissoc cached-reactions key))) (set! cached-reactions
(dissoc cached-reactions key))
(set! (.-reaction obj) nil)))
v (-deref r)] v (-deref r)]
(set! cached-reactions (assoc cached-reactions key f)) (set! cached-reactions (assoc cached-reactions key r))
(set! (.-reaction obj) r) (set! (.-reaction obj) r)
v) v)
(f)))) (f))))
(deftype Monitor [f args ^:mutable reaction] (deftype Monitor [f key ^:mutable reaction]
IReactiveAtom IReactiveAtom
IDeref IDeref
(-deref [this] (-deref [this]
(if-some [r reaction] (if-some [r reaction]
(-deref r) (-deref r)
(cached-reaction this [f args] (cached-reaction f key this)))
#(apply f args)))))
IEquiv
(-equiv [o other]
(and (instance? Monitor other)
(= key (.-key other))))
IHash
(-hash [this] (hash key))
IPrintWithWriter
(-pr-writer [a writer opts]
(-write writer (str "#<Monitor: " key " "))
(binding [*ratom-context* nil]
(pr-writer (-deref a) writer opts))
(-write writer ">")))
(defn monitor [f & args] (defn monitor [f & args]
(Monitor. f args nil)) (Monitor. #(apply f args) [f args] nil))
;;; cursor ;;; cursor