mobxjs / mobx.dart

MobX for the Dart language. Hassle-free, reactive state-management for your Dart and Flutter apps.
https://mobx.netlify.app
MIT License
2.39k stars 311 forks source link

Support late observables #919

Closed tomwyr closed 8 months ago

tomwyr commented 1 year ago

Currently, it appears not to be possible to declare a store observable that uses the late keyword. An attempt to set the observable value for the first time causes mobx to read it first throwing LateInitializationError.

class CounterStore extends _CounterStore with _$CounterStore {}

abstract class _CounterStore with Store {
  @observable
  late int counter;
}

The above will generate:

mixin _$CounterStore on _CounterStore, Store {
  late final _$counterAtom =
      Atom(name: '_CounterStore.counter', context: context);

  @override
  int get counter {
    _$counterAtom.reportRead();
    return super.counter;
  }

  @override
  set counter(int value) {
    _$counterAtom.reportWrite(value, super.counter, () { // <- reads value before the initialization has had a chance to happen
      super.counter = value;
    });
  }

  @override
  String toString() {
    return '''
counter: ${counter}
    ''';
  }
}

Consider generating code in a way, that reads the current value only if the observable is not late or it's already been initialized.

amondnet commented 8 months ago

mobx_codegen: 2.5.0