Search code examples
dartdart-polymer

Observe package from polymer dart


I am trying to use the observe package without having to have annotations in my Model, and only by raising notifyPropertyChange in setters, so to test i made the following test

import 'package:observe/observe.dart';
import 'dart:async';
import 'dart:math';
void main() {

  var dummyWatchingModel = new DummyWatchingModel();
  new Timer.periodic(new Duration(milliseconds:1000), (_){
           //calls a function that set a random value to the property in the observable model
           dummyWatchingModel.setModelProps();
      });
}

class Model extends Observable{
  int _x;
  Model(this._x);

  int get x=> _x;
  void set x(int value){
    _x = notifyPropertyChange(#_x, _x, value);
  }
}

class DummyWatchingModel{
  Model model = new Model(1); 
  final rng = new Random(); 
  anotherModel(){

    //watch for changes in model instance properties
    this.model.changes.listen((List<ChangeRecord> records) {
      for(ChangeRecord change in records){
        print(change.toString());
      }
    });
  }

  //the callback for the timer to assign a random value model.x
  setModelProps(){
    model.x = rng.nextInt(100);
    print('called...');
  }
}

i am changing the value of a property in an instance of Model using a setter that raises notifyPropertyChange but it never listens for changes, any idea why?


Solution

  • I think you want to use ChangeNotifier instead of Observable.

    I'm not sure about notifyPropertyChange but with Observable you normally need to call dirtyCheck to get notified about changes.

    I made a small example a while ago to learn how these two work:

    import 'package:observe/observe.dart';
    
    class Notifiable extends Object with ChangeNotifier {
      String _input = '';
    
      @reflectable
      get input => _input;
    
      @reflectable
      set input(val) {
        _input = notifyPropertyChange(#input, _input, val + " new");
      }
    
      Notifiable() {
        this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
      }
    }
    
    class MyObservable extends Observable {
      @observable
      String counter = '';
    
      MyObservable() {
        this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
      }
    }
    
    void main() {
      var x = new MyObservable();
      x.counter = "hallo";
      Observable.dirtyCheck();
    
      Notifiable notifiable = new Notifiable();
      notifiable.input = 'xxx';
      notifiable.input = 'yyy';
    }