Computed<T> constructor

Computed<T>(
  1. T fn(), {
  2. String? name,
  3. ReactiveContext? context,
  4. EqualityComparer<T>? equals,
  5. bool? keepAlive,
})

Creates a computed value with an optional name.

The passed in function: fn, is used to give back the computed value. Computed values can depend on other observables and computed values! This makes them both an observable and an observer. Computed values are also referred to as derived-values because they inherently derive their value from other observables. Don't underestimate the power of the computed. They are possibly the most powerful observables in your application.

A computed's value is read with the value property.

It is possible to override equality comparison (when deciding whether to notify observers) by providing an equals comparator.

keepAlive This avoids suspending computed values when they are not being observed by anything. Can potentially create memory leaks.

var x = Observable(10);
var y = Observable(10);
var total = Computed((){
  return x.value + y.value;
});

x.value = 100; // recomputes total
y.value = 100; // recomputes total again

print('total = ${total.value}'); // prints "total = 200"

A computed value is cached and it recomputes only when the dependent observables actually change. This makes them fast and you are free to use them throughout your application. Internally MobX uses a 2-phase change propagation that ensures no unnecessary computations are performed.

Implementation

factory Computed(T Function() fn,
        {String? name,
        ReactiveContext? context,
        EqualityComparer<T>? equals,
        bool? keepAlive}) =>
    Computed._(context ?? mainContext, fn,
        name: name, equals: equals, keepAlive: keepAlive);