当我使用ReactiveList
和IReactiveDerivedList
创建ViewModel,然后使用Json.net对其进行序列化和反序列化时,派生列表似乎已被破坏。我做错了什么?
viewmodel:
[DataContract]
public class TestViewModel : ReactiveObject
{
[DataMember]
public ReactiveList<int> List { get; } = new ReactiveList<int>();
public IReactiveDerivedList<int> DerivedList { get; }
public TestViewModel()
{
//DerivedList contains all elements of List that are greater than 0.
DerivedList = List.CreateDerivedCollection(v => v, v => v > 0);
}
}
序列化测试:
private void Example()
{
TestViewModel vm = new TestViewModel();
vm.List.Add(0);
vm.List.Add(1);
//vm.DerivedList now has 1 item
string json = JsonConvert.SerializeObject(vm);
TestViewModel clone = JsonConvert.DeserializeObject<TestViewModel>(json);
//vm.DerivedList now has 1 item
//clone.DerivedList now has 1 item
vm.List.Add(1);
clone.List.Add(1);
//vm.DerivedList now has 2 items
//clone.DerivedList now has 1 item
}
答案 0 :(得分:2)
我认为这里的问题是,当反序列化ViewModel时,用作派生列表源的ReactiveList也会被反序列化,这就是问题所在。
当反序列化TestViewModel时,事件的顺序如下:
最后一步是问题发生的地方。派生集合订阅旧可观察对象,而不是ReactiveList现在使用的对象。修复它的一种方法是给派生列表属性一个私有的setter,实现一个deserialization callback,并在该回调中创建派生列表。
[DataContract]
public class TestViewModel : ReactiveObject
{
[DataMember]
public ReactiveList<int> List { get; } = new ReactiveList<int>();
public IReactiveDerivedList<int> DerivedList { get; private set; }
public TestViewModel()
{
SetupRx();
}
[OnDeserialized]
internal void OnDeserialized(StreamingContext context)
{
SetupRx();
}
private void SetupRx()
{
DerivedList?.Dispose();
DerivedList = List.CreateDerivedCollection(v => v, v => v > 0);
}
}