gpt4 book ai didi

dart - 使用流进行PropertyChanges

转载 作者:行者123 更新时间:2023-12-03 02:57:41 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com