xaviergonz / mobx-keystone

A MobX powered state management solution based on data trees with first class support for Typescript, support for snapshots, patches and much more
https://mobx-keystone.js.org
MIT License
554 stars 25 forks source link

How to listen "initial" onPatches on RootStore? #520

Closed PEZO19 closed 2 weeks ago

PEZO19 commented 1 year ago

Assume RootStore's onInit starts an action.

onPatches(new RootStore({}), ()=>{})

Even instantiating here, we miss patches. Is there an official way to do that, am I missing something?

My ideas:

  1. subscribing in onInit itself, however this might be limited as the (lexical) scope/context is limited.

    onInit(){
    const disposeRootStoreOnInitPatches = onPatches(this, ()=>{
       // we can get rid of it and fallback to the original onPatches as shown above
       disposeRootStoreOnInitPatches()
    }
    }
  2. We could introduce a "RootStoreParent" / "RootRootStore". (But maybe wrong too as RootStores onInit is called before attach/listening?)

    const rootStoreParent = new RootStoreParent({})
    onPatches(rootStoreParent, ()=>{/*...*/})
    // at this point, we have a listener above RootStore
    rootStoreParent.instantiateAndAttachRootStore()
  3. Workaround: restrict onInit somehow, so it won't cause any patches to miss?