Repository navigation
Expand file tree
/
Copy pathTransform.cs
More file actions
82 lines (70 loc) · 3.64 KB
/
Copy pathTransform.cs
File metadata and controls
82 lines (70 loc) · 3.64 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
81
82
// Copyright (c) 2011-2023 Roland Pheasant. All rights reserved.
// Roland Pheasant licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System.Reactive.Linq;
using DynamicData.Kernel;
namespace DynamicData.Cache.Internal;
internal sealed class Transform<TDestination, TSource, TKey>(IObservable<IChangeSet<TSource, TKey>> source, Func<TSource, Optional<TSource>, TKey, TDestination> transformFactory, Action<Error<TSource, TKey>>? exceptionCallback = null, bool transformOnRefresh = false)
where TDestination : notnull
where TSource : notnull
where TKey : notnull
{
public IObservable<IChangeSet<TDestination, TKey>> Run() => Observable.Defer(RunImpl);
private IObservable<IChangeSet<TDestination, TKey>> RunImpl() => source.Scan(
(ChangeAwareCache<TDestination, TKey>?)null,
(cache, changes) =>
{
cache ??= new ChangeAwareCache<TDestination, TKey>(changes.Count);
foreach (var change in changes.ToConcreteType())
{
switch (change.Reason)
{
case ChangeReason.Add:
case ChangeReason.Update:
{
TDestination transformed;
if (exceptionCallback is not null)
{
try
{
transformed = transformFactory(change.Current, change.Previous, change.Key);
cache.AddOrUpdate(transformed, change.Key);
}
catch (Exception ex)
{
exceptionCallback(new Error<TSource, TKey>(ex, change.Current, change.Key));
}
}
else
{
transformed = transformFactory(change.Current, change.Previous, change.Key);
cache.AddOrUpdate(transformed, change.Key);
}
}
break;
case ChangeReason.Remove:
cache.Remove(change.Key);
break;
case ChangeReason.Refresh:
{
if (transformOnRefresh)
{
var transformed = transformFactory(change.Current, change.Previous, change.Key);
cache.AddOrUpdate(transformed, change.Key);
}
else
{
cache.Refresh(change.Key);
}
}
break;
case ChangeReason.Moved:
// Do nothing !
break;
}
}
return cache;
})
.Where(x => x is not null)
.Select(cache => cache!.CaptureChanges());
}