diff --git a/src/DynamicData/Cache/ToDictionary.cs b/src/DynamicData/Cache/ToDictionary.cs new file mode 100644 index 000000000..da8ddbaec --- /dev/null +++ b/src/DynamicData/Cache/ToDictionary.cs @@ -0,0 +1,38 @@ +using System.Reactive.Linq; +using DynamicData.Cache.Internal; + +namespace DynamicData.Cache; + +internal static class ToDictionaryEx +{ + public static IObservable> ToDictionary(this IObservable> source) + where TObject : notnull + where TKey : notnull + { + return new ToDictionary(source).Run(); + } + +} + +internal class ToDictionary(IObservable> source) + where TObject : notnull + where TKey : notnull +{ + + public IObservable> Run() => + Observable.Defer(() => + { + // maintain the dictionary + return source.Scan( + (Dictionary?)null, + (cache, changes) => + { + cache ??= new Dictionary(changes.Count); + + cache.Clone(changes); + return cache; + }); + }) + // clone so the dictionary is thread safe- + .Select(cache => new Dictionary(cache!)); +}