使用PropertyChanges的流

时间:2015-01-11 13:31:51

标签: dart dart-async

试图了解流如何工作,所以我写了这个

class ViewModelBase{
   final List<PropertyChangedRecord> _changeRecords = new List<PropertyChangedRecord>();
   Stream<PropertyChangedRecord> _changes;

   Stream<PropertyChangedRecord> get changes{
     //lazy initialization
     if(_changes==null)
       _changes = new Stream<PropertyChangedRecord>.fromIterable(_changeRecords);
     return _changes;
   }

  _raisePropertyChanged(oldValue,newValue,propertySymbol){
    if(oldValue!=newValue){
      _changeRecords.add(new PropertyChangedRecord(this, propertySymbol,oldValue,newValue));
    }
    return newValue;
  }
}

class PropertyChangedRecord{
  final ViewModelBase viewModel;
  final Symbol propertySymbol;
  final Object newValue;
  final Object oldValue;
  PropertyChangedRecord(this.viewModel,this.propertySymbol,this.oldValue,this.newValue);
}

并将其用作

void main() {
  var p = new Person('waa',13);
  p.age = 33334;
  p.name = 'dfa';
  p.changes.listen((p)=>print(p));
  p.age = 333834;
  p.name = 'dfia';
}

class Person extends ViewModelBase{
  String _name;
  String get name => _name;
  set name(String value) => _name = _raisePropertyChanged(_name,value,#name);

  int _age;
  int get age => _age;
  set age(int value) => _age = _raisePropertyChanged(_age,value,#age);

  Person(this._name,this._age);
}

并得到以下异常

Uncaught Error: Concurrent modification during iteration: Instance(length:4) of '_GrowableList'

我认为是因为当添加新的PropertyChangedRecords时,流正在从列表中删除项目,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

在流迭代列表时添加项目可能会导致错误。

您可以使用StreamController代替创建流(有关示例,请参阅How to pass a callback function to a StreamController)。

class ViewModelBase{
   //final List<PropertyChangedRecord> _changeRecords = new List<PropertyChangedRecord>();
   //Stream<PropertyChangedRecord> _changes;

  final StreamController _changeRecords = new StreamController<PropertyChangedRecord>();

   Stream<PropertyChangedRecord> get changes => _changeRecords.stream;

  _raisePropertyChanged(oldValue,newValue,propertySymbol){
    if(oldValue!=newValue){
      _changeRecords.add(new PropertyChangedRecord(this, propertySymbol,oldValue,newValue));
    }
    return newValue;
  }
}