I have the following:
(let [s1 (signaali/create-signal 0)
s2 (signaali/create-derived (fn []
(Thread/sleep 1000)
(inc @s1)))
e1 (signaali/create-effect (fn []
(println "s2:" @s2)))])
Let’s say s2 is an expensive database calculation, and I want to show a spinner while it works. Is there a way to attach an effect to say “s2 is about to re-run”?On the backend. My goal is to tell the front end to render a spinner before the calculation starts, and then render the result when it’s done
Stupid question: how do you know the “s2 is about to run” only happens when s2 is dirty? My naive belief was that that println would happen every time it was checked, not necessarily only when it is dirty
s2 is calculated only when the effects marked as stale are re-run, not when s2 is stale. it's a lazy approach.
Signaali was never tested with async derived computations, and effect-re-running concurrently with signal updates.
I suggest you to read the documentation, understand the source code, and see if it suit your use-case.
Naive approach:
(let [s1 (signaali/create-signal 0)
s2 (signaali/create-derived (fn []
(reset! spinner-spins-signal true)
(Thread/sleep 1000)
(reset! spinner-spins-signal false)
(inc @s1)))
e1 (signaali/create-effect (fn []
(println "s2:" @s2)))])
but I am not sure about the Thread/sleep in the middle of the run-fn.Maybe https://github.com/leonoel/missionary would be more suitable for what you ask.
Another solution would be that I craft a version of Signaali which would specially work with the multithreading and async computations that usually happen on the backend. That could be done as a https://www.metosin.fi/blog/2024-10-10-announcing-open-source-commercial-support gig. Let me know if you need this.
The part "s2 is about to re-run" is a bit vague, but here is what possible, let me know if it is what you want:
(let [s1 (signaali/create-signal 0)
s2 (signaali/create-derived (fn []
(Thread/sleep 1000)
(inc @s1)))
e1 (signaali/create-effect (fn []
;; here where "s2 is about to re-run" happen.
(println "s2:" @s2)
;; here is after it happened.
,))])
you can turn your spinner on and off at the places I put the 2 comments.Are you using it in the backend or in the frontend?
Alternatively, after mutating s1, is there a way to find the list of stale derived nodes?
Yes, there is a way to get a notification when any reactive node changes its status. The debug-prn function is using this mechanism, https://github.com/metosin/signaali/blob/main/src/signaali/reactive.cljc#L95-L98