55using System . Reactive . Concurrency ;
66using System . Reactive . Disposables ;
77using System . Reactive . Linq ;
8+ using System . Reactive . Threading . Tasks ;
89using System . Threading . Tasks ;
910using Bogus ;
1011using DynamicData . Kernel ;
@@ -86,9 +87,11 @@ IObservable<Animal> AddRemoveAnimals(AnimalOwner owner, int animalCount, int par
8687 . Parallelize ( animalCount , parallel , obs => obs . StressAddRemove ( owner . Animals , _ => GetRemoveTime ( ) , scheduler ) )
8788 . Finally ( owner . Animals . Dispose ) ;
8889
89- var mergeAnimals = _animalOwners . Connect ( ) . MergeManyChangeSets ( owner => owner . Animals . Connect ( ) ) ;
90-
90+ var mergeAnimals = _animalOwners . Connect ( ) . MergeManyChangeSets ( owner => owner . Animals . Connect ( ) ) . Publish ( ) ;
9191 var addingAnimals = true ;
92+ var cacheCompleted = mergeAnimals . LastOrDefaultAsync ( ) . ToTask ( ) ;
93+ using var animalResults = mergeAnimals . AsAggregator ( ) ;
94+ using var connect = mergeAnimals . Connect ( ) ;
9295
9396 // Start asynchrononously modifying the parent list and the child lists
9497 using var addAnimals = AddRemoveAnimalsStress ( ownerCount , animalCount , Environment . ProcessorCount , TaskPoolScheduler . Default )
@@ -114,8 +117,12 @@ IObservable<Animal> AddRemoveAnimals(AnimalOwner owner, int animalCount, int par
114117 }
115118 while ( addingAnimals ) ;
116119
117- // Verify the results
118- CheckResultContents ( ) ;
120+ // Wait for the source cache to finish delivering all notifications.
121+ await cacheCompleted ;
122+
123+ // Verify the results against the aggregator wired into the same Publish chain
124+ // that cacheCompleted observes.
125+ CheckResultContents ( _animalOwners . Items , _animalOwnerResults , animalResults ) ;
119126 }
120127
121128 [ Fact ]
0 commit comments