Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

batch listener notifications #11

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/src/refx/hooks.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
(react/useMemo
(fn []
[(fn [callback]
(let [key (str "use-sub-" (swap! use-sub-counter inc))]
(let [key {:index (swap! use-sub-counter inc)}]
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched the key so it can be easily sortable since use-sub-11 would come before use-sub-2 when using default string comparison.

(subs/-add-listener sub key callback)
#(subs/-remove-listener sub key)))
(fn []
Expand Down
36 changes: 34 additions & 2 deletions core/src/refx/subs.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,38 @@
(doseq [[_ sub] @sub-cache]
(dispose! sub)))

(defonce ^:private listeners-state
(atom {:counter 0 :pending (sorted-map-by :index)}))

(defn- invoke-listener
"This function is responsible for ensuring that signal listeners
(from DynamicSubs) are called before triggering regular listeners
(eg: added via use-sub hook). Listeners are triggered in the order they
were registered. This function ensures that one db update will only trigger
a single render."
[listener-key listener-fn]
(swap! listeners-state (fn [state]
(cond-> (update state :counter inc)
(not (signal? listener-key))
(update :pending assoc listener-key listener-fn))))
dehli marked this conversation as resolved.
Show resolved Hide resolved

(when (signal? listener-key)
(listener-fn))

(interop/next-tick
(fn []
(let [listener-fns (atom nil)]
(swap! listeners-state (fn [state]
(let [{:keys [counter pending] :as new-state}
(update state :counter dec)]
(if (zero? counter)
(do
(reset! listener-fns pending)
(assoc new-state :pending (sorted-map-by :index)))
new-state))))
(doseq [[_ f] @listener-fns]
(f))))))

(deftype Listeners [^:mutable listeners]
Object
(empty? [_] (empty? listeners))
Expand All @@ -84,8 +116,8 @@
(remove [_ k]
(set! listeners (dissoc listeners k)))
(notify [_]
(doseq [[_ f] listeners]
(f))))
(doseq [[k f] listeners]
(invoke-listener k f))))

(defn- make-listeners []
(Listeners. nil))
Expand Down