我们如何从
IObservable<IReadOnlyList<T>>
到 IObservableList<T>
(来自 DynamicData)?
我在我的项目中同时使用了 Reactive extensions 和 DynamicData。
我目前有一个随时间变化的字符串列表。我有一个
IObservable<IReadOnlyList<string>>
。它产生如下更新:
["A", "C", "F"]
["A", "B", "C", "F"]
["A", "B", "C"]
我想把它转换成一个
IObservableList<string>
会产生如下更新:
我试过使用
ToObservableChangeSet
扩展,但它对我的情况没有正确的行为。
代码
Subject<IReadOnlyList<string>> source = new Subject<IReadOnlyList<string>>();
IObservable<IEnumerable<string>> observableOfList = source;
IObservable<IChangeSet<string>> observableOfChangeSet = source.ToObservableChangeSet<string>();
observableOfChangeSet
.Bind(out ReadOnlyObservableCollection<string> boundCollection)
.Subscribe();
((INotifyCollectionChanged)boundCollection).CollectionChanged += OnCollectionChanged;
source.OnNext(new[] { "A", "C", "F" });
source.OnNext(new[] { "A", "B", "C" });
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Debug.WriteLine($"[{string.Join(", ", (IEnumerable<string>)sender)}] (operation: {e.Action} at index {e.NewStartingIndex})");
}
输出
[A, C, F] (operation: Reset at index -1)
[A, C, F, A] (operation: Add at index 3)
[A, C, F, A, B] (operation: Add at index 4)
[A, C, F, A, B, C] (operation: Add at index 5)
如我们所见
[A, C, F, A, B, C]
与[A, B, C]
不一样。
我也尝试过使用
EditDiff
,但这并不能保留列表的顺序。
代码
Subject<IReadOnlyList<string>> source = new Subject<IReadOnlyList<string>>();
IObservable<IEnumerable<string>> observableOfList = source;
IObservable<IChangeSet<string>> observableOfChangeSet = ObservableChangeSet.Create<string>(list =>
{
return observableOfList
.Subscribe(items => list.EditDiff(items, EqualityComparer<string>.Default));
});
observableOfChangeSet
.Bind(out ReadOnlyObservableCollection<string> boundCollection)
.Subscribe();
((INotifyCollectionChanged)boundCollection).CollectionChanged += OnCollectionChanged;
source.OnNext(new[] { "A", "C", "F" });
source.OnNext(new[] { "A", "B", "C" });
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Debug.WriteLine($"[{string.Join(", ", (IEnumerable<string>)sender)}] (operation: {e.Action} at index {e.NewStartingIndex})");
}
输出
[A, C, F] (operation: Reset at index -1)
[A, C] (operation: Remove at index -1)
[A, C, B] (operation: Add at index 2)
如我们所见
[A, C, B]
与[A, B, C]
不一样。
谢谢!
如果字符串是唯一的,为什么不在将字符串设置为键的地方使用
ToObservableChangeSet
的重载。这样,如果您的新列表不包含“F”,它就会知道您现有的“F”应该被删除。
也许有更简单的方法,但您可能需要临时插入自己的索引。如果您不需要通过绑定集合跟踪更改,您可以像这样从变更集中进行:
Subject<IReadOnlyList<string>> source = new Subject<IReadOnlyList<string>>();
IObservable<IEnumerable<string>> observableOfList = source;
IObservable<IChangeSet<(string,int),string>> observableOfChangeSet = source.Select(x =>
{
return x.Select((item, index) => (item, index));
}).ToObservableChangeSet<(string,int),string>(x=>x.Item1);
observableOfChangeSet
.Sort(SortExpressionComparer<(string, int)>.Ascending(x => x.Item2))
.OnItemAdded(x=> Debug.WriteLine($"Item {x.Item1} was added to index {x.Item2}"))
.OnItemRemoved(x => Debug.WriteLine($"Item {x.Item1} was removed from index {x.Item2}"))
.OnItemUpdated((x,prev) => Debug.WriteLine($"Item {prev.Item1} at index {prev.Item2} was updated to Item {x.Item1} at index {x.Item2}"))
.Transform(x=>
{
Debug.WriteLine($"Item: {x.Item1} at index: {x.Item2}");
return x.Item1;
})
.Bind(out ReadOnlyObservableCollection<string> boundCollection)
.Subscribe();
source.OnNext(new[] { "A", "C", "F" });
source.OnNext(new[] { "A", "B", "C" });
此代码的调试输出:
Item A was added to index 0
Item C was added to index 1
Item F was added to index 2
Item: A at index: 0
Item: C at index: 1
Item: F at index: 2
Item B was added to index 1
Item F was removed from index 2
Item A at index 0 was updated to Item A at index 0
Item C at index 1 was updated to Item C at index 2
Item: A at index: 0
Item: B at index: 1
Item: C at index: 2
我不太熟悉 DynamicData,但我相信这会给出接近预期结果的结果:
using DynamicData;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Subject<IReadOnlyList<string>> source = new Subject<IReadOnlyList<string>>();
var list = ObservableChangeSet.Create<string>(sourceList =>
{
return source
.Subscribe(newItems =>
{
sourceList.Edit(items =>
{
for (var i = 0; i < newItems.Count; i++)
{
if (items.Count <= i) items.Add(newItems[i]);
else
{
if (items[i] != newItems[i])
{
items[i] = newItems[i];
}
}
}
while (items.Count > items.Count) items.RemoveAt(items.Count - 1);
});
});
}).AsObservableList();
source.OnNext(new[] { "A", "C", "F" });
source.OnNext(new[] { "A", "B", "C", "F" });
source.OnNext(new[] { "A", "B", "C" });
Console.ReadLine();
}
}
}
不幸的是,我没有弄清楚如何获得
Add "B" at index 1
,但目前的输出如下:
AddRange. 3 changes
3 Changes
Replace. Current: B, Previous: C
Replace. Current: C, Previous: F
Add. Current: F, Previous: <None>
Remove. Current: C, Previous: <None>
编辑: 以下给出了您想要的确切输出,但我没有测试每个的性能(对于较大的列表,插入可能会变得昂贵):
using DynamicData;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Subject<IReadOnlyList<string>> source = new Subject<IReadOnlyList<string>>();
var list = ObservableChangeSet.Create<string>(sourceList =>
{
return source
.Subscribe(newItems =>
{
sourceList.Edit(items =>
{
for (var i = 0; i < newItems.Count; i++)
{
if (items.Count <= i) items.Add(newItems[i]);
else
{
if (items[i] != newItems[i])
{
items.Insert(i, newItems[i]);
}
}
}
while (items.Count > newItems.Count) items.RemoveAt(items.Count - 1);
});
});
}).AsObservableList();
source.OnNext(new[] { "A", "C", "F" });
source.OnNext(new[] { "A", "B", "C", "F" });
source.OnNext(new[] { "A", "B", "C" });
Console.ReadLine();
}
}
}
AddRange. 3 changes
Add. Current: B, Previous: <None> Index 1
Remove. Current: C, Previous: <None> Index 2
我最终写了一个自定义解决方案。
它是开源的,也有 nuget 包。
要解决原始问题,请安装以下软件包。
CollectionTracking.DynamicData
System.Reactive
然后你可以使用类似下面的方法。
using System.Reactive.Linq;
using CollectionTracking;
// ...
public static class DynamicDataExtensions
{
/// <summary>
/// Converts <see cref="IObservable{IEnumerable}"/> to <see cref="IObservableList{T}"/>.
/// Keeps the same ordering, which is why we use .GetOperations and not .EditDiff.
/// </summary>
/// <typeparam name="T">Type of items in list.</typeparam>
/// <param name="observableOfList"><see cref="IObservable{IEnumerable}"/> to convert.</param>
/// <returns>Converted <see cref="IObservableList{T}"/>.</returns>
public static IObservableList<T> ToObservableList<T>(this IObservable<IEnumerable<T>> observableOfList)
{
return observableOfList
.StartWith(Enumerable.Empty<T>())
.Buffer(2, 1)
.Select(lists => lists[0].GetOperations(lists[1]).ToChangeSet())
.AsObservableList();
}
}