Replies: 1 comment
-
It's nice to see such suggestions what take ideas from other lib use cases like mobx. Thanks. I add a comment in #604, but on second thought, this might be done by extending import { subscribe as origSubscribe } from 'valtio'
const observedMap = new WeakMap()
export const registerObservedCallbacks = (onBecomeObserved, onBecomeUnobserved) => {
...
}
export const subscribe = (proxyObject, callback) => {
let entry = observedMap.get(proxyObject)
if (!entry) {
...
}
const unsub = origSubscribe(proxyObject, callback);
++entry.observedCount
if (entry.observedCount === 1) {
entry.observedCallbacks.forEach((fn) => fn())
}
return () => {
--entry.observedCount
if (entry.observedCount === 0) {
entry.unobservedCallbacks.forEach((fn) => fn())
}
unsub()
}
} Though, this approach is sub optimal because it can't change functions that already depend on the original |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I've found I needed lazy observable behavior a few times, where I only want to subscribe to some service or async process when something is actually subscribing to some state. Mobx has 'lazy observables' which provide callbacks when an observable objects properties are first subscribed/unsubscribed: https://mobx.js.org/lazy-observables.html
I've implemented something that works reasonably well for this without adding too much payload in this PR:
#604
Would love to hear feedback on this approach.
Beta Was this translation helpful? Give feedback.
All reactions