-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathPropertyIndexer.cs
More file actions
80 lines (68 loc) · 2.19 KB
/
PropertyIndexer.cs
File metadata and controls
80 lines (68 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using ByteSync.Interfaces.Repositories;
using DynamicData;
namespace ByteSync.Repositories;
public class PropertyIndexer<TObject, TIndex> : IPropertyIndexer<TObject, TIndex>
where TObject : notnull
where TIndex : notnull
{
private Func<TObject, TIndex> _indexSelector;
private readonly Dictionary<TIndex, List<TObject>> _cache = new();
public void Initialize(SourceCache<TObject, string> sourceCache, Func<TObject, TIndex> indexSelector)
{
_indexSelector = indexSelector;
// Initializing the cache with existing objects
foreach (var obj in sourceCache.Items)
{
Update(obj);
}
// Synchronization with SourceCache
sourceCache.Connect()
.Subscribe(changes =>
{
foreach (var change in changes)
{
switch (change.Reason)
{
case ChangeReason.Add:
case ChangeReason.Update:
Update(change.Current);
break;
case ChangeReason.Remove:
Remove(change.Current);
break;
}
}
});
}
public void Update(TObject obj)
{
var index = _indexSelector(obj);
if (!_cache.TryGetValue(index, out var objects))
{
objects = new List<TObject>();
_cache[index] = objects;
}
var existingObject = objects.FirstOrDefault(o => o.Equals(obj));
if (existingObject != null)
{
objects.Remove(existingObject);
}
objects.Add(obj);
}
public void Remove(TObject obj)
{
var index = _indexSelector(obj);
if (_cache.TryGetValue(index, out var objects))
{
objects.RemoveAll(o => o.Equals(obj));
if (objects.Count == 0)
{
_cache.Remove(index);
}
}
}
public List<TObject> GetByIndex(TIndex index)
{
return _cache.TryGetValue(index, out var objects) ? objects : new List<TObject>();
}
}