dart - 使用流进行 PropertyChanges

标签 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,我该如何解决这个问题?

最佳答案

该错误可能是由于在流迭代列表时添加项目引起的。

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

关于dart - 使用流进行 PropertyChanges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27887666/

相关文章:

function - 有没有办法在 Dart 中与两种类型进行争论?

android - 无法在 flutter 中找到参数的方法 android()

dart - 我可以在Dart中异步调用非异步函数吗?

dart - 使用 Dart,如何使用 Future 正确返回 HttpResponse

flutter - 如何在小部件方法中将变量作为状态传递?

android - 在 flutter 中使用 path_provider 包时出错

dart - 等待请求正在运行

DART: future 的语法 then

flutter - 使用 getx 包重置 flutter 中 Controller 的所有值?

dart - 客户端,那么()还是其他?