Simple State Management with MobX

Kelven Galvão
Feb 7 · 3 min read

Problem

During the mobile app development, we face the necessity to share data between screens, propagate changes through the application.

To solve it, there’s a lot of approaches: Redux, BLoC, ChangeNotifier, and all of this solutions are good and solve the problem but they all have pros and cons, some are: very complex; hard to teach and learn; a lot of boilerplate code; high memory consumption.

Solution

MobX is a library of state management that have aim connect your reactive data to your UI automatically and “magically”

What is this magic? The magic is in reactions, it always re-run when data changes, notifying all the “observers”.

MobX will cause reconstruction only in observers who are using the data that has changed, that’s good for app performance.

Combined with code generation, MobX eliminates all of the boilerplate, this is also the negative point to the skeptics but it is the trade-off.

Core Concepts

Observables: Represent the reactive data, can be any object.

final name = Observable(‘Flutterando’);final object = Observable(
Community(
nome: ‘Flutterando’,
members: 5000,
),
);

Cool but it is very boilerplate, right?!

Don’t worry, the code generation will save our precious time.

You can through build_runner generate all this boilerplate code using only annotations.

@observable
String name = ‘Flutterando’;
@observable
Comunidade object = Community(nome: ‘Flutterando’, members: 5000);

Computed Values: It is data that is derived from the observables, very useful for validations.

@observable
String name;
@observable
String email;
@computed
bool get canSend => name != null && email != null;

Well, the data of MobX will be composed of observables and computed values.

Actions: It is the responsible for mutate the data(observables).

final name = Observable(‘Flutterando 4k members’);final updateMembers = Action(() {
name = ‘Flutterando 5k members’;
});
With codegen:@observable
String name = ‘Flutterando 4k members’;
@action
void updateMembers() => name = ‘Flutterando 5k members’;

Reactions: As said, the reactions are the MobX magic, it will react to our data changes and notify the observers, that will re-build the widgets with updated data.

There’s a four types of reactions, they all return a disposer that is similar to Stream.close().

Always dispose the reactions!

The reaction autorun, as the name says, it will run when declared and re-run in every changes of the data that is inside your fn.

String name = Observable(‘Flutterando 5k members’);final dispose = autorun((_) => print(name.value));name.value = ‘Flutterando 5k and hundred members’;dispose(); // fechando a reação// Output:
// Flutterando 5k members
//
Flutterando 5k and hundred members

The type reaction will be similar to autorun but won’t fire on declaration.

String name = Observable(‘Flutterando 5k members’);final dispose = reaction((_) => name, (name) => print(name));name.value = ‘Flutterando 5k and hundred members’;dispose();// Output:
//
Flutterando 5k and hundred members

The when reaction will triggers based on a condition and after triggered it auto-disposes.

String name = Observable(‘Flutterando 5k members’);final dispose = when(
(_) => name.value == ‘Flutterando 5k and hundred members’,
() => print(‘members was updated’),
);
name.value = ‘Flutterando 5k and hundred members’;dispose();// Output:
//
members was updated

The last one, asyncWhen that is the asynchronous version of when.

final name = Observable(‘Flutterando 5k members’’);void waitForCompletion() async {
await asyncWhen(() => nome.value == ‘Flutterando 5k and hundred members’);
print(‘members was updated’);
}

Observers(Widget): now using flutter_mobx, which is a package of widgets to consume MobX in the UI.

It is a widget that listen to the observables, when observable changes the reactions notifies the Observer.

Complex Observables:

With Jacob Moura contribution, now have extensions that transform List/Set/Map/Future/Stream to an observable.

  • Observable${List/Set/Map}: A Iterable that notifies the observers in every manipulation.
  • ObservableFuture: Wrap a Future in an observable and listen its value inside the Observer Widget, without the FutureBuilder necessity.
  • ObservableStream: Wrap a Stream in an observable and listen its value inside the Observer Widget, without the StreamBuilder necessity.

Be part of our community in Telegram? https://t.me/flutterando (PT-BR)

Follow us on Twitter: https://twitter.com/flutterando_ (PT-BR)

My Twittter: https://twitter.com/irvine5k

My LinkedIN: https://linkedin.com/in/irvine5k

MobX’s site : https://mobx.pub/

Flutterando

Flutterando, a maior comunidade de Dart do Brasil!

Kelven Galvão

Written by

Fluttering at https://blubybs2.com/. GitHub: https://github.com/irvine5k

Flutterando

Flutterando, a maior comunidade de Dart do Brasil!

More From Medium

More on Flutter from Flutterando

More on Flutter from Flutterando

More on Flutter from Flutterando

Aula 3— Semana do Flutter (Slidy/Modular)

55

More on Flutter from Flutterando

More on Flutter from Flutterando

Aula 4 — Semana do Flutter (Slidy/Modular)

12

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade