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 310 forks source link

Is it okay to use single observer widget for observables from multiple store instances? #1008

Closed memishood closed 1 month ago

memishood commented 1 month ago

I just have a simple question that I couldn't find any answer by checking the documentation, as I mentioned in the issue title, is it okay to use single Observer widget for observable/computed from multiple store instances? or should I create another Observer widget for each store instance?

E.g:

Stores

part 'test_store_1.g.dart';

class TestStore1 = _TestStore1 with _$TestStore1;

abstract class _TestStore1 with Store {
   @readonly
   ObservableFuture<SomeViewData>? _someViewDataObservableFuture;

   @computed
   bool get isLoading => _someViewDataObservableFuture?.status == FutureStatus.pending;

   @action 
   void getSomeViewData() {
      _someViewDataObservableFuture = ObservableFuture(
         _someUseCase.call(),
      );
   }
}
part 'test_store_2.g.dart';

class TestStore2 = _TestStore2 with _$TestStore2;

abstract class _TestStore2 with Store {
   @readonly
   ObservableFuture<SomeViewData2>? _someViewDataObservableFuture2;

   @computed
   bool get isLoading2 => _someViewDataObservableFuture2?.status == FutureStatus.pending;

   @action 
   void getSomeViewData2() {
      _someViewDataObservableFuture2 = ObservableFuture(
         _someUseCase2.call(),
      );
   }
}

UI

Widget build(BuildContext context) {
   final testStore1 = context.read<TestStore1>();
   final testStore2 = context.read<TestStore2>();

   // WAY 1
   return Observer(
      builder: (context) => testStore1.isLoading || testStore2.isLoading 
         ? CircularProgressIndicator() 
         : SomeOtherWidget(),
   );

   // WAY 2
   return Observer(
      builder: (context) => testStore1.isLoading
          ? Observer(
              builder: (context) => testStore2.isLoading 
                    ? CircularProgressIndicator() 
                    : SomeOtherWidget(),
            )
          : CircularProgressIndicator(),
    );
}
amondnet commented 1 month ago

@memishood It depends on your situation, but in the example described above, you can use only one. It is recommended to separate observers into widgets that need to be rebuilt, not by the number of observables.