Skip to content

Commit 76926d8

Browse files
authored
fix(reactiverecord): keep notification state out of derived record ToString and equality (#4482)
## Summary **Records that derive from `ReactiveRecord` print and compare only their own members.** - **`ToString()` no longer lists `Changing`, `Changed` and `ThrownExceptions`.** A derived record prints `CourseResult { StudentName = Ada, Score = 90 }`, the usual record output. - **Value equality and `GetHashCode()` ignore the base record's notification state.** Two records with equal members stay equal after either one is printed, observed or subscribed to. ## Why **The compiler-generated record members covered `ReactiveRecord`'s own properties and fields.** - `ToString()` printed the internal observable type names ahead of the record's data. - `Equals` and `GetHashCode` compared the lazily created observables, event handlers and subscription flags. Fresh records compared equal, then stopped being equal once one of them was used, so a record could get lost in a `HashSet<T>` or dictionary. Closes #4476 Closes #4477 ## Breaking changes **Behaviour change: derived records now always use value equality over their own members.** - Code that relied on two such records comparing unequal after one had been observed now sees them as equal, which is what record equality promises. ## How this was verified **Tests cover the printed output, equality and hash code after the observables are read and handlers are added, and inequality for different members.** ## Notes for the reviewer **The whole change is three members in `ReactiveRecord.cs`.** - `PrintMembers` returns `false`, and `Equals(ReactiveRecord?)` / `GetHashCode()` use only `EqualityContract`, so each derived record's synthesized code handles its own members. - The file is shared source, so `ReactiveUI.Reactive` gets the same fix. ## Checklist - [x] I have read the [Contribute guide](https://www.reactiveui.net/contribute/index.html) - [x] The PR title follows [Conventional Commits](https://www.conventionalcommits.org/) - [x] Tests cover this change, or the summary says why they do not - [x] New or changed public API has XML documentation
1 parent 1fcd23c commit 76926d8

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

‎src/ReactiveUI.Shared/ReactiveObject/ReactiveRecord.cs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using System.Diagnostics;
99
using System.Runtime.CompilerServices;
1010
using System.Runtime.Serialization;
11+
using System.Text;
1112
using System.Text.Json.Serialization;
1213

1314
#if REACTIVE_SHIM
@@ -105,11 +106,28 @@ void IReactiveObject.RaisePropertyChanged(PropertyChangedEventArgs args) =>
105106
[MethodImpl(MethodImplOptions.AggressiveInlining)]
106107
public bool AreChangeNotificationsEnabled() => IReactiveObjectExtensions.AreChangeNotificationsEnabled(this);
107108

109+
/// <summary>
110+
/// Compares only the record type. The notification state held by this base record is not data,
111+
/// so a derived record's value equality covers its own members only.
112+
/// </summary>
113+
/// <param name="other">The record to compare with.</param>
114+
/// <returns><see langword="true"/> if <paramref name="other"/> is the same record type; otherwise <see langword="false"/>.</returns>
115+
public virtual bool Equals(ReactiveRecord? other) =>
116+
ReferenceEquals(this, other) || (other is not null && EqualityContract == other.EqualityContract);
117+
118+
/// <inheritdoc/>
119+
public override int GetHashCode() => EqualityContract.GetHashCode();
120+
108121
/// <summary>Delays notifications until the return IDisposable is disposed.</summary>
109122
/// <returns>A disposable which when disposed will send delayed notifications.</returns>
110123
[MethodImpl(MethodImplOptions.AggressiveInlining)]
111124
public IDisposable DelayChangeNotifications() => IReactiveObjectExtensions.DelayChangeNotifications(this);
112125

126+
/// <summary>Prints no members, so a derived record's ToString shows only its own members.</summary>
127+
/// <param name="builder">The builder the derived record writes its members to.</param>
128+
/// <returns><see langword="false"/>, because this record prints no members.</returns>
129+
protected virtual bool PrintMembers(StringBuilder builder) => false;
130+
113131
/// <summary>Adds a property-changing event handler.</summary>
114132
/// <param name="handler">The handler to add.</param>
115133
[MethodImpl(MethodImplOptions.AggressiveInlining)]

‎src/tests/ReactiveUI.Tests/ReactiveObjects/ReactiveRecordTests.cs‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,52 @@ public async Task SuppressChangeNotificationsShouldWork()
286286
await Assert.That(fixture.AreChangeNotificationsEnabled()).IsTrue();
287287
}
288288

289+
/// <summary>Test that ToString prints only the derived record's own members.</summary>
290+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
291+
[Test]
292+
public async Task ToStringShouldPrintOnlyDerivedMembers()
293+
{
294+
const int AgeValue = 25;
295+
var fixture = new TestRecord { Name = "Test", Age = AgeValue };
296+
297+
await Assert.That(fixture.ToString()).IsEqualTo("TestRecord { Name = Test, Age = 25 }");
298+
}
299+
300+
/// <summary>Test that records with equal members stay equal after their reactive state is used.</summary>
301+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
302+
[Test]
303+
public async Task RecordsWithEqualMembersShouldBeEqualAfterReactiveStateIsUsed()
304+
{
305+
const int AgeValue = 25;
306+
var first = new TestRecord { Name = "Test", Age = AgeValue };
307+
var second = new TestRecord { Name = "Test", Age = AgeValue };
308+
309+
_ = first.Changing;
310+
_ = first.Changed;
311+
_ = first.ThrownExceptions;
312+
first.PropertyChanged += static (_, _) => { };
313+
first.PropertyChanging += static (_, _) => { };
314+
315+
using (Assert.Multiple())
316+
{
317+
await Assert.That(first.Equals(second)).IsTrue();
318+
await Assert.That(first == second).IsTrue();
319+
await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode());
320+
}
321+
}
322+
323+
/// <summary>Test that records with different members are not equal.</summary>
324+
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
325+
[Test]
326+
public async Task RecordsWithDifferentMembersShouldNotBeEqual()
327+
{
328+
const int AgeValue = 25;
329+
var first = new TestRecord { Name = "Test", Age = AgeValue };
330+
var second = new TestRecord { Name = "Other", Age = AgeValue };
331+
332+
await Assert.That(first.Equals(second)).IsFalse();
333+
}
334+
289335
/// <summary>Test that ThrownExceptions observable is initialized.</summary>
290336
/// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
291337
[Test]

0 commit comments

Comments
 (0)
⌂ 换网址