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.4k stars 310 forks source link

[question] between getIt and provider which one is more suited for getting and properly disposing/destroying a store instance when the widget that uses it is also disposed/destroyed #802

Open mruizdev opened 2 years ago

mruizdev commented 2 years ago

hello i am using mobx for quite a while, and i really like it, but it bugs me a little that i dont know what happens to the store reference as soon as the widget that it references is removed from the widget tree. I am using GetIt to get a reference of the store inside the a "Page" Widget

class MyPage extends StatelessWidget {

  final _store = GetIt.instance<MyPageStore>();

  @override
  Widget build(BuildContext context) {
  // code blabla
  }
}

i would like that that '_store' instance when the MyPage widget is destroyed would be destroyed as well, i have read that maybe using provider to get that store would do the dispose when the widget is no longer on the widget tree but im not sure, also i would like to know if i use a StatefulWidget would help to always dispose a store when the widget is no longer in use

  class MyPage extends StatefulWidget {
  const MyPage({Key? key}) : super(key: key);

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  final _store =  GetIt.instance<MyPageStore>();

  @override
  Widget build(BuildContext context) {
     // code blabla
      }
}

so regarding disposing/destroying the store when the widget that uses it is also disposed/destroyed which approach is best? statelessWidget + getIt, statefulWidget + getIt, statelessWidget + provider? other???

samus commented 2 years ago

It depends on how you're registering MyPageStore with GetIt. If you're using the registerSingleton method it will always remain by default unless you call the unregister method in GetIt. If you're using registerFactory it will vend out an instance which will have the same lifecycle as if your widget instantiated the MyPageStore itself. GetIt doesn't hold references to objects created by factories. If you need to do some cleanup on the store, use a StatefulWidget and put your cleanup code in the dispose method of the widget's State object.