-
Notifications
You must be signed in to change notification settings - Fork 1
Add NotifyPropertyChangedExtensions (WatchProperty, WatchProperties, WatchAllProperties) #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
ecc704e
Add NotifyPropertyChangedExtensions with WatchProperty, WatchProperti…
Copilot a293621
Use field keyword instead of explicit backing fields in FakeNotifyPro…
Copilot 012164f
Consolidate NotifyPropertyChanged tests to <3 per method
Copilot d325350
Update NotifyPropertyChangedExtensionsTests.cs
Tyrrrz 00d870f
Validate DeclaringType in WatchProperty/WatchProperties; fix watchIni…
Copilot f9da9e0
Rename `received` to `values` in WatchProperty_Test per suggestion
Copilot e891d02
Rename StringValue/IntValue to StringProperty/IntProperty; add braces…
Copilot 9d579e6
Update NotifyPropertyChangedExtensionsTests.cs
Tyrrrz 75ee22d
Remove try/catch around watchInitialValue and return Disposable directly
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
255 changes: 255 additions & 0 deletions
255
PowerKit.Tests/Extensions/NotifyPropertyChangedExtensionsTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,255 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.ComponentModel; | ||
| using System.Runtime.CompilerServices; | ||
| using FluentAssertions; | ||
| using PowerKit.Extensions; | ||
| using Xunit; | ||
|
|
||
| namespace PowerKit.Tests.Extensions; | ||
|
|
||
| file class FakeNotifyPropertyChanged : INotifyPropertyChanged | ||
| { | ||
| public event PropertyChangedEventHandler? PropertyChanged; | ||
|
|
||
| private string? _stringValue; | ||
| private int _intValue; | ||
|
|
||
| public string? StringValue | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
| { | ||
| get => _stringValue; | ||
| set | ||
| { | ||
| _stringValue = value; | ||
| OnPropertyChanged(); | ||
| } | ||
| } | ||
|
|
||
| public int IntValue | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
| { | ||
| get => _intValue; | ||
| set | ||
| { | ||
| _intValue = value; | ||
| OnPropertyChanged(); | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
|
|
||
| public void RaiseAllPropertiesChanged() => | ||
| PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty)); | ||
|
|
||
| private void OnPropertyChanged([CallerMemberName] string? propertyName = null) => | ||
| PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); | ||
| } | ||
|
|
||
| public class NotifyPropertyChangedExtensionsTests | ||
| { | ||
| [Fact] | ||
| public void WatchProperty_FiresOnChange_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged { StringValue = "initial" }; | ||
| var received = new List<string?>(); | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
|
|
||
| // Act | ||
| using var _ = obj.WatchProperty(x => x.StringValue, v => received.Add(v)); | ||
| obj.StringValue = "hello"; | ||
| obj.StringValue = "world"; | ||
|
|
||
| // Assert | ||
| received.Should().Equal("hello", "world"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperty_WatchInitialValue_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged { StringValue = "initial" }; | ||
| var received = new List<string?>(); | ||
|
|
||
| // Act | ||
| using var _ = obj.WatchProperty( | ||
| x => x.StringValue, | ||
| v => received.Add(v), | ||
| watchInitialValue: true | ||
| ); | ||
| obj.StringValue = "hello"; | ||
|
|
||
| // Assert | ||
| received.Should().Equal("initial", "hello"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperty_DoesNotFireForOtherProperties_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var received = new List<string?>(); | ||
|
|
||
| // Act | ||
| using var _ = obj.WatchProperty(x => x.StringValue, v => received.Add(v)); | ||
| obj.IntValue = 42; | ||
|
|
||
| // Assert | ||
| received.Should().BeEmpty(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperty_FiresOnAllPropertiesChanged_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged { StringValue = "initial" }; | ||
| var received = new List<string?>(); | ||
|
|
||
| // Act | ||
| using var _ = obj.WatchProperty(x => x.StringValue, v => received.Add(v)); | ||
| obj.RaiseAllPropertiesChanged(); | ||
|
|
||
| // Assert | ||
| received.Should().Equal("initial"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperty_Unsubscribes_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var received = new List<string?>(); | ||
|
|
||
| // Act | ||
| var subscription = obj.WatchProperty(x => x.StringValue, v => received.Add(v)); | ||
| obj.StringValue = "hello"; | ||
| subscription.Dispose(); | ||
| obj.StringValue = "world"; | ||
|
|
||
| // Assert | ||
| received.Should().Equal("hello"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperty_NonPropertyExpression_Throws_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
|
|
||
| // Act & assert | ||
| var act = () => obj.WatchProperty(x => x.StringValue!.ToUpper(), _ => { }); | ||
| act.Should().Throw<ArgumentException>(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperties_FiresOnMatchingChange_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var callCount = 0; | ||
|
|
||
| // Act | ||
| using var _ = obj.WatchProperties( | ||
| [x => x.StringValue, x => (object?)x.IntValue], | ||
| () => callCount++ | ||
| ); | ||
| obj.StringValue = "hello"; | ||
| obj.IntValue = 42; | ||
|
|
||
| // Assert | ||
| callCount.Should().Be(2); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperties_WatchInitialValue_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var callCount = 0; | ||
|
|
||
| // Act | ||
| using var _ = obj.WatchProperties( | ||
| [x => x.StringValue, x => (object?)x.IntValue], | ||
| () => callCount++, | ||
| watchInitialValue: true | ||
| ); | ||
|
|
||
| // Assert | ||
| callCount.Should().Be(1); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperties_FiresOnAllPropertiesChanged_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var callCount = 0; | ||
|
|
||
| // Act | ||
| using var _ = obj.WatchProperties([x => x.StringValue], () => callCount++); | ||
| obj.RaiseAllPropertiesChanged(); | ||
|
|
||
| // Assert | ||
| callCount.Should().Be(1); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperties_Unsubscribes_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var callCount = 0; | ||
|
|
||
| // Act | ||
| var subscription = obj.WatchProperties([x => x.StringValue], () => callCount++); | ||
| obj.StringValue = "hello"; | ||
| subscription.Dispose(); | ||
| obj.StringValue = "world"; | ||
|
|
||
| // Assert | ||
| callCount.Should().Be(1); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchAllProperties_FiresOnAnyChange_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var callCount = 0; | ||
|
|
||
| // Act | ||
| using var _ = obj.WatchAllProperties(() => callCount++); | ||
| obj.StringValue = "hello"; | ||
| obj.IntValue = 42; | ||
|
|
||
| // Assert | ||
| callCount.Should().Be(2); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchAllProperties_WatchInitialValue_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var callCount = 0; | ||
|
|
||
| // Act | ||
| using var _ = obj.WatchAllProperties(() => callCount++, watchInitialValue: true); | ||
|
|
||
| // Assert | ||
| callCount.Should().Be(1); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchAllProperties_Unsubscribes_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var callCount = 0; | ||
|
|
||
| // Act | ||
| var subscription = obj.WatchAllProperties(() => callCount++); | ||
| obj.StringValue = "hello"; | ||
| subscription.Dispose(); | ||
| obj.StringValue = "world"; | ||
|
|
||
| // Assert | ||
| callCount.Should().Be(1); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| #nullable enable | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.ComponentModel; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Linq; | ||
| using System.Linq.Expressions; | ||
| using System.Reflection; | ||
|
|
||
| namespace PowerKit.Extensions; | ||
|
|
||
| #if !POWERKIT_INCLUDE_COVERAGE | ||
| [ExcludeFromCodeCoverage] | ||
| #endif | ||
| internal static class NotifyPropertyChangedExtensions | ||
| { | ||
| extension<TOwner>(TOwner owner) | ||
| where TOwner : INotifyPropertyChanged | ||
| { | ||
| /// <summary> | ||
| /// Subscribes to changes of the specified property on the owner object. | ||
| /// The returned <see cref="IDisposable" /> can be disposed to unsubscribe. | ||
| /// </summary> | ||
| public IDisposable WatchProperty<TProperty>( | ||
| Expression<Func<TOwner, TProperty>> propertyExpression, | ||
| Action<TProperty> callback, | ||
| bool watchInitialValue = false | ||
| ) | ||
| { | ||
| var memberExpression = propertyExpression.Body as MemberExpression; | ||
| if (memberExpression?.Member is not PropertyInfo property) | ||
| throw new ArgumentException( | ||
| "Provided expression must reference a property.", | ||
| nameof(propertyExpression) | ||
| ); | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
Tyrrrz marked this conversation as resolved.
|
||
|
|
||
| var getValue = propertyExpression.Compile(); | ||
|
|
||
| void OnPropertyChanged(object? sender, PropertyChangedEventArgs args) | ||
| { | ||
| if ( | ||
| string.IsNullOrWhiteSpace(args.PropertyName) | ||
| || string.Equals(args.PropertyName, property.Name, StringComparison.Ordinal) | ||
| ) | ||
| { | ||
| callback(getValue(owner)); | ||
| } | ||
| } | ||
|
|
||
| owner.PropertyChanged += OnPropertyChanged; | ||
|
|
||
| if (watchInitialValue) | ||
| callback(getValue(owner)); | ||
|
|
||
| return Disposable.Create(() => owner.PropertyChanged -= OnPropertyChanged); | ||
|
Tyrrrz marked this conversation as resolved.
|
||
| } | ||
|
Tyrrrz marked this conversation as resolved.
|
||
|
|
||
| /// <summary> | ||
| /// Subscribes to changes of the specified properties on the owner object. | ||
| /// The returned <see cref="IDisposable" /> can be disposed to unsubscribe. | ||
| /// </summary> | ||
| public IDisposable WatchProperties( | ||
| IEnumerable<Expression<Func<TOwner, object?>>> propertyExpressions, | ||
| Action callback, | ||
| bool watchInitialValue = false | ||
| ) | ||
| { | ||
| var properties = propertyExpressions | ||
| .Select(expression => | ||
| { | ||
| var memberExpression = | ||
| expression.Body as MemberExpression | ||
| // Because the expression is typed to return an object, the compiler will | ||
| // implicitly wrap it in a conversion unary expression if it's of any other type. | ||
| ?? (expression.Body as UnaryExpression)?.Operand as MemberExpression; | ||
|
|
||
| if (memberExpression?.Member is not PropertyInfo property) | ||
| throw new ArgumentException( | ||
| "Provided expression must reference a property.", | ||
| nameof(propertyExpressions) | ||
| ); | ||
|
Tyrrrz marked this conversation as resolved.
|
||
|
|
||
| return property; | ||
| }) | ||
|
Tyrrrz marked this conversation as resolved.
|
||
| .ToArray(); | ||
|
|
||
| void OnPropertyChanged(object? sender, PropertyChangedEventArgs args) | ||
| { | ||
| if ( | ||
| string.IsNullOrWhiteSpace(args.PropertyName) | ||
| || properties.Any(p => | ||
| string.Equals(args.PropertyName, p.Name, StringComparison.Ordinal) | ||
| ) | ||
| ) | ||
| { | ||
| callback(); | ||
| } | ||
| } | ||
|
|
||
| owner.PropertyChanged += OnPropertyChanged; | ||
|
|
||
| if (watchInitialValue) | ||
| callback(); | ||
|
|
||
| return Disposable.Create(() => owner.PropertyChanged -= OnPropertyChanged); | ||
| } | ||
|
Tyrrrz marked this conversation as resolved.
|
||
|
|
||
| /// <summary> | ||
| /// Subscribes to changes of all properties on the owner object. | ||
| /// The returned <see cref="IDisposable" /> can be disposed to unsubscribe. | ||
| /// </summary> | ||
| public IDisposable WatchAllProperties(Action callback, bool watchInitialValue = false) | ||
| { | ||
| void OnPropertyChanged(object? sender, PropertyChangedEventArgs args) => callback(); | ||
| owner.PropertyChanged += OnPropertyChanged; | ||
|
|
||
| if (watchInitialValue) | ||
| callback(); | ||
|
|
||
| return Disposable.Create(() => owner.PropertyChanged -= OnPropertyChanged); | ||
|
Tyrrrz marked this conversation as resolved.
|
||
| } | ||
|
Tyrrrz marked this conversation as resolved.
|
||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.