对 PropertyChanges 使用流

Using a stream for PropertyChanges

为了理解流是如何工作的,所以我写了这篇文章

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 时流正在从列表中删除项目,我该如何解决这个问题?

错误可能是由于在流迭代列表时添加了一个项目造成的。

您可以使用 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;
  }
}