How to observe simple variable in dart language

gblaszczyk picture gblaszczyk · Aug 30, 2013 · Viewed 7k times · Source

My question is: How to observe changes on simple variable like String or num? I know that you can easy observe object like this:

observe(t, (e) => print ("Value changed"));

but How to do this on simple variable?

Answer

Seth Ladd picture Seth Ladd · Aug 31, 2013

(This answer applies to Polymer.dart.)

The observe package includes a wrapper for single observable values: ObservableBox.

import 'package:observe/observe.dart';
import 'dart:async';

void main() {
  ObservableBox myValue = new ObservableBox('hello');

  myValue.changes.listen((List<ChangeRecord> records) {
    PropertyChangeRecord record = records[0] as PropertyChangeRecord;

    print('${record.field} changed, it is now ${myValue.value}');
  });

  new Timer.periodic(const Duration(seconds: 1), (t) {
    myValue.value = new DateTime.now();
  });
}

There is no way to observe a top-level or function-scope single string, boolean, int, or double without using ObservableBox.

If the string, boolean, int, or double is a field of a class, you can use ObservableMixin and the @observable annotation.

class Foo extends Object with ObservableMixin {
  @observable String bar = '';
}

You can then get notified when an instance of Foo changes:

foo.changes.listen((List<ChangeRecord> records) {
  // ...
});