LegendApp / legend-state

Legend-State is a super fast and powerful state library that enables fine-grained reactivity and easy automatic persistence
https://legendapp.com/open-source/state/
MIT License
2.61k stars 77 forks source link

Lazy Observables / "onUnobserved" Listener #273

Open ps73 opened 3 months ago

ps73 commented 3 months ago

Is there currently any option to set listeners to observe state of an observable such as Lazy Observables in Mox?

In my case I want to listen to an "onObserved" and "onUnobserved" event of an observable.

Wrapping something inside an computed helps me to track if it is observed, but I cannot listen for the "unobservation".

Maybe this references to #202?

jmeistrich commented 3 months ago

This is something that I’m aiming to enable soon, as well as #202, but it’s unfortunately more complex than in mobx because:

  1. Listeners are removed and re-added when an observing context re-runs, so it would need to be done in a cleanup pass after all actions are complete.
  2. unObserved is harder because listeners both up and down the hierarchy are run when a node changes. So a node would only be considered unobserved when all of its ancestors and descendants are unobserved.

These are both solveable, and we need to solve them soon. It’s just going to take some extra thought to do it in the most performant way, because it would be easy to blow out performance by walking up and down a node tree too often. So we may need some kind of reference counting mechanism - I’m not sure yet...

jmeistrich commented 2 months ago

FYI I just released version 3.0 alpha which solves #202 but this one is not quite solved yet. The second problem I mentioned above is solved, but we’re not yet piping through observed/unobserved events. So this is just a progress update and I’ll try to get to that soon.

I’m curious though, what is your use case for tracking observed/unobserved events?