Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ Structure public and internal mutation/query methods so cheap checks reject no-o
The .NET 10 and later JIT can inline some methods that contain `try`/`finally`. The presence of a lock is not enough to decide whether to split a method. Use measurements to justify a split on modern targets. Keep large branches and uncommon work out of the steady-state path:

- Keep hot steady-state paths (`Count`, indexer reads, `AsSpan`, observerless fast checks, lazy-initialized pipeline/channel reads) small and mark tiny wrappers `[MethodImpl(MethodImplOptions.AggressiveInlining)]`.
- Read lazy-initialized references (`_streamPipeline`, `_eventChannel`) via `Volatile.Read` on the warm path, and split lock-protected initialization (`EnsureEventProcessorStarted`, `EnsurePipelineCreated`), buffer resizing, contention fallback, and exception throwing into `[MethodImpl(MethodImplOptions.NoInlining)]` slow-path methods.
- Read lazy-initialized references (`_streamPipeline`, `_eventChannel`) via `Volatile.Read` on the warm path, and split lock-protected initialization (`EnsureEventProcessorStarted`, `CreateStreamObservable`), buffer resizing, contention fallback, and exception throwing into `[MethodImpl(MethodImplOptions.NoInlining)]` slow-path methods.

### 3. Single-Item vs Batch and Zero-Throttle Paths

Expand Down
135 changes: 107 additions & 28 deletions README.md

Large diffs are not rendered by default.

45 changes: 45 additions & 0 deletions docs/migration-v6-to-v7.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Migrating from v5 or v6 to v7

Version 7 adopts ReactiveUI namespace standards and targets `.NET 10`, `.NET 11`, and `.NET Framework 4.7` to `4.8.1`. The NuGet package names stay `ReactiveList` and `ReactiveList.Reactive`.

## Steps

1. Update your `using` directives to the new root namespaces in the table below.
2. Rebuild your project before changing any logic. Almost every upgrade error is a namespace import.
3. Work through the breaking changes below.
4. Keep `ReactiveList` and `ReactiveList.Reactive` in separate assemblies when possible. Referencing both in one file puts two `Subscribe` extension methods in scope.

## Namespaces

| Package | v5 / v6 namespace | v7 namespace |
| --- | --- | --- |
| `ReactiveList` | `CP.Primitives` | `ReactiveList` |
| `ReactiveList` | `CP.Primitives.Collections` | `ReactiveList.Collections` |
| `ReactiveList` | `CP.Primitives.Core` | `ReactiveList.Core` |
| `ReactiveList` | `CP.Primitives.Views` | `ReactiveList.Views` |
| `ReactiveList.Reactive` | `CP.Reactive` | `ReactiveList.Reactive` |
| `ReactiveList.Reactive` | `CP.Reactive.Collections` | `ReactiveList.Reactive.Collections` |
| `ReactiveList.Reactive` | `CP.Reactive.Core` | `ReactiveList.Reactive.Core` |
| `ReactiveList.Reactive` | `CP.Reactive.Views` | `ReactiveList.Reactive.Views` |

Version 7 also adds `ReactiveList.Queries` and `ReactiveList.Reactive.Queries` for live queries.

## Breaking changes

| Change | What to do |
| --- | --- |
| Every library class is sealed. | You cannot derive from a collection or view. Wrap one in your own type instead. |
| The abstract base class of the quaternary collections is gone. | Use `QuaternaryList<T>`, `QuaternaryDictionary<TKey, TValue>` or their interfaces. |
| `Reactive2DList<T>` does not derive from `ReactiveList<ReactiveList<T>>`. | It implements `IReactiveList<ReactiveList<T>>`, so pass it through that interface. |
| A filtered view always lists items in source order. | An item that starts to match after an update goes to its source position, not to the end. Remove any code that relied on the old position. |
| Some parameter names changed to match their interfaces. | Update calls that use named arguments. |

## New features

The [README](../README.md) describes each of these:

- Live queries, started from a collection's `Live` property.
- `DeferNotifications()`, which groups several writes into one notification.
- `IVersionedSnapshotSource<T>`, which pairs a copy of a collection with the version it matches.
- `BatchResetLimit` on views.
- `ReactiveSourceOptions.ItemsAreImmutable`.
20 changes: 17 additions & 3 deletions src/ReactiveList/Internal/StreamProjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ internal sealed class StreamProjection<TSource, T> : IDisposable, IObserver<Vers
/// <summary>The comparer that finds an element by value, or <see langword="null"/> for the default search.</summary>
private readonly IEqualityComparer<T>? _itemComparer;

/// <summary>The comparer that finds the exact occurrence of an element before the search by value, or <see langword="null"/>.</summary>
private readonly IEqualityComparer<T>? _occurrenceComparer;

/// <summary>The cached property-change notification.</summary>
private readonly PropertyChangedEventArgs _changedArgs;

Expand Down Expand Up @@ -138,19 +141,22 @@ internal sealed class StreamProjection<TSource, T> : IDisposable, IObserver<Vers
/// <param name="changedProperty">The property name raised after each applied drain.</param>
/// <param name="synchronizeReads">Whether the facade reads the collection independently of the dispatcher.</param>
/// <param name="itemComparer">Finds an element by value for element types whose default equality allocates, or <see langword="null"/>.</param>
/// <param name="occurrenceComparer">Finds the exact occurrence of an element whose identity is not its own reference, or <see langword="null"/>.</param>
internal StreamProjection(
IReactiveSource<TSource>? source,
Func<TSource, T> select,
ProjectionRules<T> rules,
string changedProperty,
bool synchronizeReads = false,
IEqualityComparer<T>? itemComparer = null)
IEqualityComparer<T>? itemComparer = null,
IEqualityComparer<T>? occurrenceComparer = null)
{
ArgumentExceptionHelper.ThrowIfNull(select);
ArgumentExceptionHelper.ThrowIfNull(rules);

_source = source;
_itemComparer = itemComparer;
_occurrenceComparer = occurrenceComparer;
_ignoreRefreshes = source is IReactiveSourceWithOptions { Options.ItemsAreImmutable: true };
_select = select;
_rules = rules;
Expand Down Expand Up @@ -1092,6 +1098,14 @@ private bool RemoveOne(T item)
/// <summary>Finds an occurrence, preferring reference identity over value equality.</summary>
/// <param name="item">The item to find.</param>
/// <returns>The index, or -1.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int IndexOf(T item) => _itemComparer is null ? Target.FindLast(item) : Target.FindLast(item, _itemComparer);
private int IndexOf(T item)
{
// Two elements can be equal by value yet stand for different source items, so the exact occurrence wins when it is present.
if (_occurrenceComparer is { } occurrence && Target.FindLast(item, occurrence) is >= 0 and var exact)
{
return exact;
}

return _itemComparer is null ? Target.FindLast(item) : Target.FindLast(item, _itemComparer);
}
}
6 changes: 6 additions & 0 deletions src/ReactiveList/Queries/LiveBinding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ internal LiveBinding(LiveTryMap<TRaw, T> map, IEqualityComparer<TRaw> comparer,
Comparer = comparer;
SameRaw = sameRaw;
Identity = new(comparer);

// A value type has no instance identity, so the search by value already finds the occurrence.
Occurrence = typeof(TRaw).IsValueType ? null : new(Identity);
}

/// <summary>Gets the recorded filters and projections.</summary>
Expand All @@ -36,6 +39,9 @@ internal LiveBinding(LiveTryMap<TRaw, T> map, IEqualityComparer<TRaw> comparer,
/// <summary>Gets the comparer that tells whether two source items are the same occurrence: the same instance for reference types.</summary>
internal LiveIdentityComparer<TRaw> Identity { get; }

/// <summary>Gets the comparer that finds the entry holding one source item instance, or <see langword="null"/> for value types.</summary>
internal LiveEntryOccurrenceComparer<TRaw, T>? Occurrence { get; }

/// <summary>Gets the test for two source items being the same entry of a keyed source, or <see langword="null"/>.</summary>
internal Func<TRaw, TRaw, bool>? SameRaw { get; }

Expand Down
26 changes: 26 additions & 0 deletions src/ReactiveList/Queries/LiveEntryOccurrenceComparer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright (c) ReactiveUI and Contributors. All rights reserved.
// ReactiveUI and Contributors licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.

#if REACTIVELIST_REACTIVE
namespace ReactiveList.Reactive.Queries;
#else
namespace ReactiveList.Queries;
#endif

/// <summary>Treats two entries as the same occurrence when they hold the same source item instance.</summary>
/// <typeparam name="TRaw">The source item type.</typeparam>
/// <typeparam name="T">The item type the query exposes.</typeparam>
/// <param name="identity">Tells whether two source items are the same occurrence.</param>
internal sealed class LiveEntryOccurrenceComparer<TRaw, T>(LiveIdentityComparer<TRaw> identity) : IEqualityComparer<LiveEntry<TRaw, T>>
where TRaw : notnull
where T : notnull
{
/// <inheritdoc/>
public bool Equals(LiveEntry<TRaw, T>? x, LiveEntry<TRaw, T>? y) =>
ReferenceEquals(x, y) || (x is not null && y is not null && identity.Equals(x.Raw, y.Raw));

/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetHashCode(LiveEntry<TRaw, T> obj) => identity.GetHashCode(obj.Raw);
}
2 changes: 1 addition & 1 deletion src/ReactiveList/Queries/LiveMergeSubscription.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ internal LiveMergeSubscription(
LiveBinding<TRaw, T>.Matches,
binding.SameRaw is null ? null : binding.SameEntry,
previousIsReliable: binding.SameRaw is null);
_projection = new(source, binding.CreateEntry, rules, "Count");
_projection = new(source, binding.CreateEntry, rules, "Count", occurrenceComparer: binding.Occurrence);
}

/// <inheritdoc/>
Expand Down
2 changes: 1 addition & 1 deletion src/ReactiveList/Queries/LiveSetEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ internal LiveSetEngine(
LiveBinding<TRaw, T>.Matches,
binding.SameRaw is null ? null : binding.SameEntry,
previousIsReliable: binding.SameRaw is null);
_projection = new(source, binding.CreateEntry, rules, "Count");
_projection = new(source, binding.CreateEntry, rules, "Count", occurrenceComparer: binding.Occurrence);
var skip = shape.Window.Skip;
var take = shape.Window.Take;
if (shape.Window.HasSources)
Expand Down
26 changes: 25 additions & 1 deletion src/tests/ReactiveList.Tests/GroupedReactiveViewFuzzTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,11 @@ private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan thr
}

list.Add(ViewFuzzSupport.Sentinel);
await ViewFuzzSupport.SettleAsync(() => view.TryGetValue(ViewFuzzSupport.Sentinel % GroupCount, out var members) && members.Contains(ViewFuzzSupport.Sentinel));

// The view changes on its scheduler thread, so wait for every group, not only the one that holds the last item written.
var expected = list.ToArray().GroupBy(static item => item % GroupCount).ToDictionary(static group => group.Key, ViewFuzzSupport.Sorted);
await ViewFuzzSupport.SettleAsync(() => Matches(view, expected));

await Assert.That(view.Count).IsEqualTo(expected.Count);
foreach (var pair in expected)
{
Expand All @@ -76,4 +78,26 @@ private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan thr

await Assert.That(view.Groups.Count).IsEqualTo(expected.Count);
}

/// <summary>Checks that the view holds exactly the expected groups and members.</summary>
/// <param name="view">The view.</param>
/// <param name="expected">The sorted members of each expected group.</param>
/// <returns><see langword="true"/> when the view matches.</returns>
private static bool Matches(GroupedReactiveView<int, int> view, Dictionary<int, int[]> expected)
{
if (view.Count != expected.Count)
{
return false;
}

foreach (var pair in expected)
{
if (!view.TryGetValue(pair.Key, out var members) || !ViewFuzzSupport.Sorted(members).SequenceEqual(pair.Value))
{
return false;
}
}

return true;
}
}
25 changes: 25 additions & 0 deletions src/tests/ReactiveList.Tests/LiveQuerySelectManyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,31 @@ public async Task Replace_WithAnEqualCopy_SwapsTheSubscription()
await Assert.That(counter.Active).IsEqualTo(1);
}

/// <summary>After one of two equal items is removed, an in-place change that takes the other out of the filter releases its subscription.</summary>
/// <param name="removeFirst">Whether to remove the first of the two equal items, not the second.</param>
/// <returns>A task representing the asynchronous test.</returns>
[Test]
[Arguments(true)]
[Arguments(false)]
public async Task RemoveOneOfTwoEqualItems_ThenChangeTheOther_ReleasesItsSubscription(bool removeFirst)
{
var first = new LiveQueryRow(0, 0, 0);
using var list = new ReactiveList<LiveQueryRow>([first, first with { }]);
var counter = new LiveQuerySubscriptionCounter();
using var subscription = list.Live.Where(static r => r.Tag != KeptTag).SelectMany(counter.Observe).Subscribe(new LiveQueryRecorder<int>());
await TestWaitHelpers.WaitUntilAsync(() => counter.Active == TestData.TestValueTwo);

list.RemoveAt(removeFirst ? 0 : 1);
var kept = list[0];
kept.Change(KeptTag, 0);

// Assigning an item to its own position is how a list reports that the item changed in place.
list[0] = kept;

await TestWaitHelpers.WaitUntilAsync(() => counter.Active == 0);
await Assert.That(counter.Unsubscribed).IsEqualTo(TestData.TestValueTwo);
}

/// <summary>An item whose observable fails synchronously while the query is rebuilt ends the merge and releases every subscription.</summary>
/// <returns>A task representing the asynchronous test.</returns>
[Test]
Expand Down
27 changes: 27 additions & 0 deletions src/tests/ReactiveList.Tests/LiveSequenceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,33 @@ public async Task Remove_EntryMissingFromTheSequence_ClearsTheMark()
await Assert.That(sequence.Target.Count).IsEqualTo(0);
}

/// <summary>The occurrence comparer matches entries that hold the same source item instance, not equal copies.</summary>
/// <returns>A task representing the asynchronous test.</returns>
[Test]
public async Task OccurrenceComparer_MatchesTheSameInstanceOnly()
{
var comparer = Binding.Occurrence!;
var row = new LiveQueryRow(0, 0, 0);
var entry = Binding.CreateEntry(row);

await Assert.That(comparer.Equals(entry, entry)).IsTrue();
await Assert.That(comparer.Equals(entry, Binding.CreateEntry(row))).IsTrue();
await Assert.That(comparer.Equals(entry, Binding.CreateEntry(row with { }))).IsFalse();
await Assert.That(comparer.GetHashCode(entry)).IsEqualTo(comparer.GetHashCode(Binding.CreateEntry(row)));
await Assert.That(comparer.Equals(entry, null)).IsFalse();
await Assert.That(comparer.Equals(null, entry)).IsFalse();
}

/// <summary>A binding over a value type has no occurrence comparer, because the search by value already finds the occurrence.</summary>
/// <returns>A task representing the asynchronous test.</returns>
[Test]
public async Task OccurrenceComparer_ValueTypeSource_IsAbsent()
{
var binding = new LiveBinding<KeyValuePair<int, int>, KeyValuePair<int, int>>(PassPair, LiveKeyValueComparer<int, int>.Instance, null);

await Assert.That(binding.Occurrence).IsNull();
}

/// <summary>Replacing an entry that is marked included but is not in the sequence inserts the replacement.</summary>
/// <returns>A task representing the asynchronous test.</returns>
[Test]
Expand Down
4 changes: 3 additions & 1 deletion src/tests/ReactiveList.Tests/ReactiveViewFuzzTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,11 @@ static async (initial, ops) =>
}

list.Add(ViewFuzzSupport.Sentinel);
await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Holds(view.Items, ViewFuzzSupport.Sentinel));

// The view changes on its scheduler thread, so wait for every item, not only the last one written.
var expected = ViewFuzzSupport.Sorted(list.Where(ViewFuzzSupport.Passes));
await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Sorted(view.Items).SequenceEqual(expected));

await Assert.That(ViewFuzzSupport.Sorted(view.Items)).IsEquivalentTo(expected, CollectionOrdering.Matching);
},
iter: ThrottledIterations,
Expand Down
7 changes: 5 additions & 2 deletions src/tests/ReactiveList.Tests/SortedReactiveViewFuzzTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,13 @@ private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan thr
}

list.Add(ViewFuzzSupport.Sentinel);
await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Holds(view.Items, ViewFuzzSupport.Sentinel));

// The view changes on its scheduler thread and the sentinel sorts ahead of other items, so it can show before the rest. Wait for every item.
var expected = ViewFuzzSupport.Sorted(list);
await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Sorted(view.Items).SequenceEqual(expected));

var items = ViewFuzzSupport.Copy(view.Items);
await Assert.That(ViewFuzzSupport.Sorted(items)).IsEquivalentTo(ViewFuzzSupport.Sorted(list), CollectionOrdering.Matching);
await Assert.That(ViewFuzzSupport.Sorted(items)).IsEquivalentTo(expected, CollectionOrdering.Matching);
for (var i = 1; i < items.Length; i++)
{
await Assert.That(CoarseComparer.Compare(items[i - 1], items[i])).IsLessThanOrEqualTo(0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ public async Task QueuedBurst_PreservesAllCurrentKeysAndValues(bool throttled, C
source.AddOrUpdate(index % KeyCount, index * ParityDivisor);
}

await scheduler.WorkAvailable.WaitAsync(DispatchTimeout, cancellationToken);
scheduler.RunAll();
// The dictionary delivers the burst from a background reader, so the first queued callback may cover only part of it.
var settled = await scheduler.RunUntilAsync(() => Matches(view, source), DispatchTimeout, cancellationToken);

await Assert.That(settled).IsTrue();
await Assert.That(view.Count).IsEqualTo(KeyCount);
var seen = new HashSet<int>();
foreach (var item in view.Items)
Expand All @@ -65,4 +66,26 @@ public async Task QueuedBurst_PreservesAllCurrentKeysAndValues(bool throttled, C
scheduler.RunAll();
await Assert.That(view.Items).IsEmpty();
}

/// <summary>Checks that the view holds every key with the value the source holds for it.</summary>
/// <param name="view">The view.</param>
/// <param name="source">The source dictionary.</param>
/// <returns><see langword="true"/> when the view matches the source.</returns>
private static bool Matches(DynamicSecondaryIndexDictionaryReactiveView<int, int> view, QuaternaryDictionary<int, int> source)
{
if (view.Count != KeyCount)
{
return false;
}

foreach (var item in view.Items)
{
if (!source.TryGetValue(item.Key, out var value) || value != item.Value)
{
return false;
}
}

return true;
}
}
Loading
Loading