diff --git a/src/re_frame/interop.clj b/src/re_frame/interop.clj index 5a4b24f..f3c086e 100644 --- a/src/re_frame/interop.clj +++ b/src/re_frame/interop.clj @@ -23,6 +23,8 @@ (defonce ^:private executor (Executors/newSingleThreadExecutor)) +(defonce ^:private on-dispose-callbacks (atom {})) + (defn next-tick [f] (let [bound-f (bound-fn [& args] (apply f args))] (.execute ^Executor executor bound-f)) @@ -56,15 +58,21 @@ (deref [_] (f)))) (defn add-on-dispose! - "No-op in JVM Clojure, since for testing purposes, we don't care about - releasing resources for efficiency purposes." + "On JVM Clojure, use an atom to register `f` to be invoked when `dispose!` is + invoked with `a-ratom`." [a-ratom f] - nil) + (do (swap! on-dispose-callbacks update a-ratom (fnil conj []) f) + nil)) -(defn dispose! [a-ratom] - "No-op in JVM Clojure, since for testing purposes, we don't care about - releasing resources for efficiency purposes." - nil) +(defn dispose! + "On JVM Clojure, invoke all callbacks registered with `add-on-dispose!` for + `a-ratom`." + [a-ratom] + ;; Try to replicate reagent's behavior, releasing resources first then + ;; invoking callbacks + (let [callbacks (get @on-dispose-callbacks a-ratom)] + (swap! on-dispose-callbacks dissoc a-ratom) + (doseq [f callbacks] (f)))) (defn set-timeout! "Note that we ignore the `ms` value and just invoke the function, because diff --git a/test/re_frame/subs_test.cljs b/test/re_frame/subs_test.cljs index 8850a9e..9a92fa8 100644 --- a/test/re_frame/subs_test.cljs +++ b/test/re_frame/subs_test.cljs @@ -98,6 +98,22 @@ (subs/subscribe [:side-effecting-handler :a]) ;; this should be handled by cache (is (= @side-effect-atom 2)))) +;============== test clear-subscription-cache! ================ + +(deftest test-clear-subscription-cache! + (re-frame/reg-sub + :clear-subscription-cache! + (fn clear-subs-cache [db _] 1)) + + (testing "cold cache" + (is (nil? (subs/cache-lookup [:clear-subscription-cache!])))) + (testing "cache miss" + (is (= 1 @(subs/subscribe [:clear-subscription-cache!]))) + (is (some? (subs/cache-lookup [:clear-subscription-cache!])))) + (testing "clearing" + (subs/clear-subscription-cache!) + (is (nil? (subs/cache-lookup [:clear-subscription-cache!]))))) + ;============== test register-pure macros ================ (deftest test-reg-sub-macro