Skip to content

Instantly share code, notes, and snippets.

@MCarlomagno
Created January 12, 2022 21:01
Show Gist options
  • Save MCarlomagno/028d6bb477842787424f4999967a1851 to your computer and use it in GitHub Desktop.
Save MCarlomagno/028d6bb477842787424f4999967a1851 to your computer and use it in GitHub Desktop.
class MyReactiveService with ReactiveServiceMixin {
ReactiveValue<int> _counterOne = ReactiveValue<int>(0);
ReactiveValue<int> _counterTwo = ReactiveValue<int>(0);
int get counterOne => _counterOne.value;
int get counterTwo => _counterTwo.value;
ProposalSheetFormService() {
listenToReactiveValues([_counterOne, _counterTwo]);
}
setCounterOne(int value) {
_counterOne.value = value;
}
setCounterTwo(int value) {
_counterTwo.value = value;
}
}
// note we are not using BaseViewModel but ReactiveViewModel instead
class FirstViewModel extends ReactiveViewModel {
// we obtain the singleton instance of the reactive service
// using getIt library, also used in stacked architecture
final _myReactiveService = locator<MyReactiveService>();
// we listen the updates in counterOne and counterTwo values
// and rebuild the FirstView each time they change
int get counterOne => _myReactiveService.counterOne;
int get counterTwo => _myReactiveService.counterOne;
// here the magic happens, when we call setCounter functions inside this viewmodel
// the second viewmodel also receives the change and re-renders the view
setCounterOne(int value) => _myReactiveService.setCounterOne(value);
setCounterTwo(int value) => _myReactiveService.setCounterTwo(value);
// this method permits the viewmodel to call
// notifyListeners() function after some reactive
// value inside the reactive service canges
@override
List<ReactiveServiceMixin> get reactiveServices => [_myReactiveService];
}
class SecondViewModel extends ReactiveViewModel {
final _myReactiveService = locator<MyReactiveService>();
int get counterOne => _myReactiveService.counterOne;
int get counterTwo => _myReactiveService.counterOne;
setCounterOne(int value) => _myReactiveService.setCounterOne(value);
setCounterTwo(int value) => _myReactiveService.setCounterTwo(value);
setCounterTwo(int value) {
_counterTwo.value = value;
}
@override
List<ReactiveServiceMixin> get reactiveServices => [_myReactiveService];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment