Skip to content

Commit 5bf069d

Browse files
authored
Feature: Use Flag instead of Counter for TransformManyAsync/TransformOnObservable (reactivemarbles#844)
* Updated TransformManyAsync and TransformOnObservable to avoid using a counter and use a parent update flag instead * Fixed handling of Exceptions for TransformManySafeAsync scenarios * Minor code clean-up / improvements
1 parent fb86420 commit 5bf069d

8 files changed

Lines changed: 97 additions & 76 deletions

‎src/DynamicData/Cache/Internal/MergeChangeSets.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
using System.Reactive.Concurrency;
66
using System.Reactive.Linq;
7+
using DynamicData.Internal;
78

89
namespace DynamicData.Cache.Internal;
910

@@ -33,7 +34,7 @@ public IObservable<IChangeSet<TObject, TKey>> Run() => Observable.Create<IChange
3334
.Synchronize(locker)
3435
.Do(cache.Clone)
3536
.MergeMany(mc => mc.Source.Do(static _ => { }, observer.OnError))
36-
.Subscribe(
37+
.SubscribeSafe(
3738
changes => changeTracker.ProcessChangeSet(changes, observer),
3839
observer.OnError,
3940
observer.OnCompleted);

‎src/DynamicData/Cache/Internal/MergeMany.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Reactive.Disposables;
66
using System.Reactive.Linq;
77
using System.Reactive.Subjects;
8+
using DynamicData.Internal;
89

910
namespace DynamicData.Cache.Internal;
1011

@@ -39,9 +40,9 @@ public IObservable<TDestination> Run() => Observable.Create<TDestination>(
3940
.SubscribeMany((t, key) =>
4041
{
4142
counter.Added();
42-
return _observableSelector(t, key).Synchronize(locker).Finally(() => counter.Finally()).Subscribe(observer.OnNext, _ => { }, () => { });
43+
return _observableSelector(t, key).Synchronize(locker).Finally(() => counter.Finally()).Subscribe(observer.OnNext, static _ => { });
4344
})
44-
.Subscribe(_ => { }, observer.OnError, observer.OnCompleted);
45+
.SubscribeSafe(observer.OnError, observer.OnCompleted);
4546

4647
return new CompositeDisposable(disposable, counter);
4748
});

‎src/DynamicData/Cache/Internal/MergeManyCacheChangeSets.cs‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,11 @@ public IObservable<IChangeSet<TDestination, TDestinationKey>> Run() => Observabl
3131
var shared = source
3232
.Transform((obj, key) => new ChangeSetCache<TDestination, TDestinationKey>(selector(obj, key).Synchronize(locker)))
3333
.Synchronize(locker)
34-
.Do(cache.Clone)
35-
.Do(_ => parentUpdate = true)
34+
.Do(changes =>
35+
{
36+
cache.Clone(changes);
37+
parentUpdate = true;
38+
})
3639
.Publish();
3740

3841
// Merge the child changeset changes together and apply to the tracker
@@ -47,12 +50,13 @@ public IObservable<IChangeSet<TDestination, TDestinationKey>> Run() => Observabl
4750
var subRemove = shared
4851
.OnItemRemoved(changeSetCache => changeTracker.RemoveItems(changeSetCache.Cache.KeyValues), invokeOnUnsubscribe: false)
4952
.OnItemUpdated((_, prev) => changeTracker.RemoveItems(prev.Cache.KeyValues))
50-
.Do(_ =>
51-
{
52-
changeTracker.EmitChanges(observer);
53-
parentUpdate = false;
54-
})
55-
.Subscribe();
53+
.SubscribeSafe(
54+
_ =>
55+
{
56+
changeTracker.EmitChanges(observer);
57+
parentUpdate = false;
58+
},
59+
observer.OnError);
5660

5761
return new CompositeDisposable(shared.Connect(), subMergeMany, subRemove);
5862
});

‎src/DynamicData/Cache/Internal/MergeManyCacheChangeSetsSourceCompare.cs‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,11 @@ public IObservable<IChangeSet<TDestination, TDestinationKey>> Run() => Observabl
3838
var shared = source
3939
.Transform((obj, key) => new ChangeSetCache<ParentChildEntry, TDestinationKey>(_changeSetSelector(obj, key).Synchronize(locker)))
4040
.Synchronize(locker)
41-
.Do(cache.Clone)
42-
.Do(_ => parentUpdate = true)
41+
.Do(changes =>
42+
{
43+
cache.Clone(changes);
44+
parentUpdate = true;
45+
})
4346
.Publish();
4447

4548
// Merge the child changeset changes together and apply to the tracker
@@ -63,12 +66,13 @@ public IObservable<IChangeSet<TDestination, TDestinationKey>> Run() => Observabl
6366

6467
// Subscribe to handle all the requested changes and emit them downstream
6568
var subParent = parentObservable
66-
.Do(_ =>
67-
{
68-
changeTracker.EmitChanges(observer);
69-
parentUpdate = false;
70-
})
71-
.Subscribe();
69+
.SubscribeSafe(
70+
_ =>
71+
{
72+
changeTracker.EmitChanges(observer);
73+
parentUpdate = false;
74+
},
75+
observer.OnError);
7276

7377
return new CompositeDisposable(shared.Connect(), subMergeMany, subParent);
7478
}).TransformImmutable(entry => entry.Child);

‎src/DynamicData/Cache/Internal/MergeManyListChangeSets.cs‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,13 @@ public IObservable<IChangeSet<TDestination>> Run() => Observable.Create<IChangeS
4545
var subRemove = shared
4646
.OnItemRemoved(clonedList => changeTracker.RemoveItems(clonedList.List), invokeOnUnsubscribe: false)
4747
.OnItemUpdated((_, prev) => changeTracker.RemoveItems(prev.List))
48-
.Do(_ =>
49-
{
50-
changeTracker.EmitChanges(observer);
51-
parentUpdate = false;
52-
})
53-
.Subscribe();
48+
.SubscribeSafe(
49+
_ =>
50+
{
51+
changeTracker.EmitChanges(observer);
52+
parentUpdate = false;
53+
},
54+
observer.OnError);
5455

5556
return new CompositeDisposable(shared.Connect(), subMergeMany, subRemove);
5657
});

‎src/DynamicData/Cache/Internal/TransformManyAsync.cs‎

Lines changed: 41 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -21,62 +21,68 @@ public IObservable<IChangeSet<TDestination, TDestinationKey>> Run() => Observabl
2121
{
2222
var locker = new object();
2323
var cache = new Cache<ChangeSetCache<TDestination, TDestinationKey>, TKey>();
24-
var updateCounter = 0;
25-
26-
// Transformation Function:
27-
// Create the Child Observable by invoking the async selector, appending the counter and the synchronize
28-
// Pass the result to a new ChangeSetCache instance.
29-
ChangeSetCache<TDestination, TDestinationKey> Transform_(TSource obj, TKey key) => new(
30-
Observable.Defer(() => selector(obj, key))
31-
.Do(_ => Interlocked.Increment(ref updateCounter))
32-
.Synchronize(locker!));
24+
var parentUpdate = false;
3325

3426
// This is manages all of the changes
3527
var changeTracker = new ChangeSetMergeTracker<TDestination, TDestinationKey>(() => cache.Items, comparer, equalityComparer);
3628

29+
// Transform Helper
30+
async Task<IObservable<IChangeSet<TDestination, TDestinationKey>>> InvokeSelector(TSource obj, TKey key)
31+
{
32+
if (errorHandler != null)
33+
{
34+
try
35+
{
36+
return await selector(obj, key).ConfigureAwait(false);
37+
}
38+
catch (Exception e)
39+
{
40+
errorHandler.Invoke(new Error<TSource, TKey>(e, obj, key));
41+
return Observable.Empty<IChangeSet<TDestination, TDestinationKey>>();
42+
}
43+
}
44+
45+
return await selector(obj, key).ConfigureAwait(false);
46+
}
47+
48+
// Transformation Function:
49+
// Create the Child Observable by invoking the async selector, appending the synchronize, and creating a new ChangeSetCache instance.
50+
ChangeSetCache<TDestination, TDestinationKey> Transform_(TSource obj, TKey key) =>
51+
new(Observable.Defer(() => InvokeSelector(obj, key)).Synchronize(locker!));
52+
3753
// Transform to a cache changeset of child caches, synchronize, clone changes to the local copy, and publish.
38-
// Increment updateCounter BEFORE the lock so that incoming changesets will cause the downstream changeset to be delayed
39-
// until all pending changesets have been handled.
40-
var shared =
41-
(errorHandler is null ? source.Transform(Transform_) : source.TransformSafe(Transform_, errorHandler))
42-
.Do(_ => Interlocked.Increment(ref updateCounter))
43-
.Synchronize(locker)
44-
.Do(cache.Clone)
45-
.Publish();
54+
var shared = source
55+
.Transform(Transform_)
56+
.Synchronize(locker)
57+
.Do(
58+
changes =>
59+
{
60+
cache.Clone(changes);
61+
parentUpdate = true;
62+
})
63+
.Publish();
4664

4765
// Merge the child changeset changes together and apply to the tracker
48-
// Emit the changeset if there are no other pending changes
66+
// Emit the changeset if not currently handling a parent stream update
4967
var subMergeMany = shared
5068
.MergeMany(cacheChangeSet => cacheChangeSet.Source)
5169
.SubscribeSafe(
52-
changes => changeTracker.ProcessChangeSet(changes, Interlocked.Decrement(ref updateCounter) == 0 ? observer : null),
70+
changes => changeTracker.ProcessChangeSet(changes, !parentUpdate ? observer : null),
5371
observer.OnError);
5472

5573
// When a source item is removed, all of its sub-items need to be removed
56-
// Emit the changeset if there are no other pending changes
74+
// Emit any pending changes
5775
var subRemove = shared
5876
.OnItemRemoved(changeSetCache => changeTracker.RemoveItems(changeSetCache.Cache.KeyValues), invokeOnUnsubscribe: false)
5977
.OnItemUpdated((_, prev) => changeTracker.RemoveItems(prev.Cache.KeyValues))
6078
.SubscribeSafe(
6179
_ =>
6280
{
63-
if (Interlocked.Decrement(ref updateCounter) == 0)
64-
{
65-
changeTracker.EmitChanges(observer);
66-
}
81+
changeTracker.EmitChanges(observer);
82+
parentUpdate = false;
6783
},
6884
observer.OnError,
69-
() =>
70-
{
71-
if (Volatile.Read(ref updateCounter) == 0)
72-
{
73-
observer.OnCompleted();
74-
}
75-
else
76-
{
77-
changeTracker.MarkComplete();
78-
}
79-
});
85+
observer.OnCompleted);
8086

8187
return new CompositeDisposable(shared.Connect(), subMergeMany, subRemove);
8288
});

‎src/DynamicData/Cache/Internal/TransformOnObservable.cs‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
using System.Reactive.Disposables;
66
using System.Reactive.Linq;
77
using DynamicData.Internal;
8-
using DynamicData.Kernel;
98

109
namespace DynamicData.Cache.Internal;
1110

@@ -18,18 +17,20 @@ public IObservable<IChangeSet<TDestination, TKey>> Run() => Observable.Create<IC
1817
{
1918
var cache = new ChangeAwareCache<TDestination, TKey>();
2019
var locker = new object();
21-
var pendingUpdates = 0;
20+
var parentUpdate = false;
2221

23-
// Helper to emit any pending changes when all the updates have been handled
24-
void EmitChanges()
22+
// Helper to emit any pending changes when appropriate
23+
void EmitChanges(bool fromParent)
2524
{
26-
if (Interlocked.Decrement(ref pendingUpdates) == 0)
25+
if (fromParent || !parentUpdate)
2726
{
2827
var changes = cache!.CaptureChanges();
2928
if (changes.Count > 0)
3029
{
3130
observer.OnNext(changes);
3231
}
32+
33+
parentUpdate = false;
3334
}
3435
}
3536

@@ -38,27 +39,25 @@ void EmitChanges()
3839
IObservable<TDestination> CreateSubObservable(TSource obj, TKey key) =>
3940
transform(obj, key)
4041
.DistinctUntilChanged()
41-
.Do(_ => Interlocked.Increment(ref pendingUpdates))
4242
.Synchronize(locker!)
4343
.Do(val => cache!.AddOrUpdate(val, key));
4444

45-
// Always increment the counter OUTSIDE of the lock to signal any thread currently holding the lock
46-
// to not emit the changeset because more changes are incoming.
45+
// Flag a parent update is happening once inside the lock
4746
var shared = source
48-
.Do(_ => Interlocked.Increment(ref pendingUpdates))
4947
.Synchronize(locker!)
48+
.Do(_ => parentUpdate = true)
5049
.Publish();
5150

52-
// Use MergeMany because it automatically handles Add/Update/Remove and OnCompleted/OnError correctly
51+
// MergeMany automatically handles Add/Update/Remove and OnCompleted/OnError correctly
5352
var subMerged = shared
5453
.MergeMany(CreateSubObservable)
55-
.SubscribeSafe(_ => EmitChanges(), observer.OnError, observer.OnCompleted);
54+
.SubscribeSafe(_ => EmitChanges(fromParent: false), observer.OnError, observer.OnCompleted);
5655

5756
// Subscribe to the shared Observable to handle Remove events. MergeMany will unsubscribe from the sub-observable,
5857
// but the corresponding key value needs to be removed from the Cache so the remove is observed downstream.
5958
var subRemove = shared
6059
.OnItemRemoved((_, key) => cache!.Remove(key), invokeOnUnsubscribe: false)
61-
.SubscribeSafe(_ => EmitChanges());
60+
.SubscribeSafe(_ => EmitChanges(fromParent: true), observer.OnError);
6261

6362
return new CompositeDisposable(shared.Connect(), subMerged, subRemove);
6463
});

‎src/DynamicData/Internal/ObservableEx.cs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,14 @@ public static IDisposable SubscribeSafe<T>(this IObservable<T> observable, Actio
1414
public static IDisposable SubscribeSafe<T>(this IObservable<T> observable, Action<T> onNext, Action<Exception> onError) =>
1515
observable.SubscribeSafe(Observer.Create(onNext, onError));
1616

17-
public static IDisposable SubscribeSafe<T>(this IObservable<T> observable, Action<T> onNext, Action onComplete) =>
18-
observable.SubscribeSafe(Observer.Create(onNext, onComplete));
17+
public static IDisposable SubscribeSafe<T>(this IObservable<T> observable, Action<Exception> onError, Action onComplete) =>
18+
observable.SubscribeSafe(Observer.Create(Stub<T>.Ignore, onError, onComplete));
1919

20-
public static IDisposable SubscribeSafe<T>(this IObservable<T> observable, Action<T> onNext) =>
21-
observable.SubscribeSafe(Observer.Create(onNext));
20+
public static IDisposable SubscribeSafe<T>(this IObservable<T> observable, Action<Exception> onError) =>
21+
observable.SubscribeSafe(Observer.Create(Stub<T>.Ignore, onError));
22+
23+
private static class Stub<T>
24+
{
25+
public static readonly Action<T> Ignore = static _ => { };
26+
}
2227
}

0 commit comments

Comments
 (0)