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.57k stars 75 forks source link

Async batching? #318

Open evelant opened 1 week ago

evelant commented 1 week ago

After reading through the docs it's not clear to me if there is a strict requirement that all batches be sync operations. Sometimes it's important to batch changes in async contexts. Can I use startBatch at the beginning of an async fn then endBatch at the end or will that cause problems? Looking at the implementation in batching.ts it seems to be making the assumption that a batch is always a single synchronous function call.

jmeistrich commented 1 week ago

A batch has to be synchronous because batching tweaks the process in the core change notification system, making all changes that happen between start/end part of the batch. Allowing that to be async could potentially cause huge problems because no observables would notify until the end of the async function. If that async function took a super long time it could effectively freeze the app.

If you need to batch things asynchronously it's best to just make changes into local variables and then set them onto observables in a batch after all the async processes are finished.

Does that make sense? Or do you have some ideas for how to make async batching work?