Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

mobx.dart

mobx for the dart language. hassle-free, reactive state-management for your dart and flutter apps.

supercharge the state-management in your dart apps with transparent functional reactive programming (tfrp)

mobx is a state-management library that makes it simple to connect the reactive data of your application with the ui. this wiring is completely automatic and feels very natural. as the application-developer, you focus purely on what reactive-data needs to be consumed in the ui (and elsewhere) without worrying about keeping the two in sync.

it’s not really magic but it does have some smarts around what is being consumed (observables) and where (reactions), and automatically tracks it for you. when the observables change, all reactions are re-run. what’s interesting is that these reactions can be anything from a simple console log, a network call to re-rendering the ui.

mobx has been a very effective library for the javascript apps and this port to the dart language aims to bring the same levels of productivity.

core concepts

mobx triad

at the heart of mobx are three important concepts: observables, actions and reactions.

observables

observables represent the reactive-state of your application. they can be simple scalars to complex object trees. by
defining the state of the application as a tree of observables, you can expose a reactive-state-tree that the ui
(or other observers in the app) consume.

a simple reactive-counter is represented by the following observable:

import 'package:mobx/mobx.dart';

final counter = observable(0);

more complex observables, such as classes, can be created as well.

class counter {
  counter() {
    increment = action(_increment);
  }

  final _value = observable(0);
  int get value => _value.value;

  set value(int newvalue) => _value.value = newvalue;
  action increment;

  void _increment() {
    _value.value++;
  }
}

on first sight, this does look like some boilerplate code which can quickly go out of hand!
this is why we added mobx_codegen to the mix that allows you to replace the above code with the following:

import 'package:mobx/mobx.dart';

part 'counter.g.dart';

class counter = counterbase with _$counter;

abstract class counterbase with store {
  @observable
  int value = 0;

  @action
  void increment() {
    value++;
  }
}

note the use of annotations to mark the observable properties of the class. yes, there is some header boilerplate here
but its fixed for any class. as you build more complex classes this boilerplate
will fade away and you will mostly focus on the code within the braces.

note: annotations are available via the mobx_codegen package.

readonly

if you want to reduce your code you may want to swap @observable for @readonly.
for every private variable it generates a public getter such that the client of your store
can’t change its value. read more about it here

computed observables

what can be derived, should be derived. automatically.

the state of your application consists of core-state and derived-state. the core-state is state inherent to the domain you are dealing with. for example, if you have a contact entity, the firstname and lastname form the core-state of contact. however, fullname is derived-state, obtained by combining firstname and lastname.

such derived state, that depends on core-state or other derived-state is called a computed observable. it is automatically kept in sync when its underlying observables change.

state in mobx = core-state + derived-state

import 'package:mobx/mobx.dart';

part 'contact.g.dart';

class contact = contactbase with _$contact;

abstract class contactbase with store {
  @observable
  string firstname;

  @observable
  string lastname;

  @computed
  string get fullname => '$firstname, $lastname';

}

in the example above fullname is automatically kept in sync if either firstname and/or lastname changes.

actions

actions are how you mutate the observables. rather than mutating them directly, actions
add a semantic meaning to the mutations. for example, instead of just doing value++,
firing an increment() action carries more meaning. besides, actions also batch up
all the notifications and ensure the changes are notified only after they complete.
thus the observers are notified only upon the atomic completion of the action.

note that actions can also be nested, in which case the notifications go out
when the top-most action has completed.

final counter = observable(0);

final increment = action((){
  counter.value++;
});

when creating actions inside a class, you can take advantage of annotations!

import 'package:mobx/mobx.dart';

part 'counter.g.dart';

class counter = counterbase with _$counter;

abstract class counterbase with store {
  @observable
  int value = 0;

  @action
  void increment() {
    value++;
  }
}

asynchronous actions

mobx.dart handles asynchronous actions automatically and does not require wrapping the code with runinaction.

@observable
string stuff = '';

@observable
loading = false;

@action
future<void> loadstuff() async {
  loading = true; //this notifies observers
  stuff = await fetchstuff();
  loading = false; //this also notifies observers
}

reactions

reactions complete the mobx triad of observables, actions and reactions. they are
the observers of the reactive-system and get notified whenever an observable they
track is changed. reactions come in few flavors as listed below. all of them
return a reactiondisposer, a function that can be called to dispose the reaction.

one striking feature of reactions is that they automatically track all the observables without any explicit wiring. the act of reading an observable within a reaction is enough to track it!

the code you write with mobx appears to be literally ceremony-free!

reactiondisposer autorun(function(reaction) fn)

runs the reaction immediately and also on any change in the observables used inside
fn.

import 'package:mobx/mobx.dart';

string greeting = observable('hello world');

final dispose = autorun((_){
  print(greeting.value);
});

greeting.value = 'hello mobx';

// done with the autorun()
dispose();


// prints:
// hello world
// hello mobx

reactiondisposer reaction<t>(t function(reaction) predicate, void function(t) effect)

monitors the observables used inside the predicate() function and runs the effect() when
the predicate returns a different value. only the observables inside predicate() are tracked.

import 'package:mobx/mobx.dart';

string greeting = observable('hello world');

final dispose = reaction((_) => greeting.value, (msg) => print(msg));

greeting.value = 'hello mobx'; // cause a change

// done with the reaction()
dispose();


// prints:
// hello mobx

reactiondisposer when(bool function(reaction) predicate, void function() effect)

monitors the observables used inside predicate() and runs the effect() when it returns true. after the effect() is run, when automatically disposes itself. so you can think of when as a one-time reaction. you can also dispose when() pre-maturely.

import 'package:mobx/mobx.dart';

string greeting = observable('hello world');

final dispose = when((_) => greeting.value == 'hello mobx', () => print('someone greeted mobx'));

greeting.value = 'hello mobx'; // causes a change, runs effect and disposes


// prints:
// someone greeted mobx

future<void> asyncwhen(bool function(reaction) predicate)

similar to when but returns a future, which is fulfilled when the predicate() returns true. this is a convenient way of waiting for the predicate() to turn true.

final completed = observable(false);

void waitforcompletion() async {
  await asyncwhen(() => _completed.value == true);

  print('completed');
}

observer

one of the most visual reactions in the app is the ui. the observer widget (which is part of the flutter_mobx package), provides a granular observer of the observables used in its builder function. whenever these observables change, observer rebuilds and renders.

below is the counter example in its entirety.

import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:mobx/mobx.dart';

part 'counter.g.dart';

class counter = counterbase with _$counter;

abstract class counterbase with store {
  @observable
  int value = 0;

  @action
  void increment() {
    value++;
  }
}

class counterexample extends statefulwidget {
  const counterexample({key key}) : super(key: key);

  @override
  _counterexamplestate createstate() => _counterexamplestate();
}

class _counterexamplestate extends state<counterexample> {
  final _counter = counter();

  @override
  widget build(buildcontext context) => scaffold(
        appbar: appbar(
          title: const text('counter'),
        ),
        body: center(
          child: column(
            mainaxisalignment: mainaxisalignment.center,
            children: <widget>[
              const text(
                'you have pushed the button this many times:',
              ),
              observer(
                  builder: (_) => text(
                        '${_counter.value}',
                        style: const textstyle(fontsize: 20),
                      )),
            ],
          ),
        ),
        floatingactionbutton: floatingactionbutton(
          onpressed: _counter.increment,
          tooltip: 'increment',
          child: const icon(icons.add),
        ),
      );
}

Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.