-
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 all commits
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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
105 changes: 105 additions & 0 deletions
105
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,105 @@ | ||
| 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; | ||
|
|
||
| public string? StringProperty | ||
| { | ||
| get; | ||
| set | ||
| { | ||
| field = value; | ||
| OnPropertyChanged(); | ||
| } | ||
| } | ||
|
|
||
| public int IntProperty | ||
| { | ||
| get; | ||
| set | ||
| { | ||
| field = value; | ||
| OnPropertyChanged(); | ||
| } | ||
| } | ||
|
|
||
| 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_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged { StringProperty = "initial" }; | ||
| var values = new List<string?>(); | ||
|
|
||
| // Act | ||
| var sub = obj.WatchProperty(x => x.StringProperty, v => values.Add(v), true); | ||
|
|
||
| obj.StringProperty = "hello"; | ||
| obj.IntProperty = 42; | ||
| obj.RaiseAllPropertiesChanged(); | ||
| sub.Dispose(); | ||
| obj.StringProperty = "world"; | ||
|
|
||
| // Assert | ||
| values.Should().Equal("initial", "hello", "hello"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchProperties_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var callCount = 0; | ||
|
|
||
| // Act | ||
| var sub = obj.WatchProperties( | ||
| [x => x.StringProperty, x => x.IntProperty], | ||
| () => callCount++, | ||
| true | ||
| ); | ||
|
|
||
| obj.StringProperty = "hello"; | ||
| obj.IntProperty = 42; | ||
| obj.RaiseAllPropertiesChanged(); | ||
| sub.Dispose(); | ||
| obj.StringProperty = "world"; | ||
|
|
||
| // Assert | ||
| callCount.Should().Be(4); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void WatchAllProperties_Test() | ||
| { | ||
| // Arrange | ||
| var obj = new FakeNotifyPropertyChanged(); | ||
| var callCount = 0; | ||
|
|
||
| // Act | ||
| var sub = obj.WatchAllProperties(() => callCount++, true); | ||
| obj.StringProperty = "hello"; | ||
| obj.IntProperty = 42; | ||
| sub.Dispose(); | ||
| obj.StringProperty = "world"; | ||
|
|
||
| // Assert | ||
| callCount.Should().Be(3); | ||
| } | ||
| } |
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,144 @@ | ||
| #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 | ||
| // The compiler implicitly wraps value types in a conversion expression when | ||
| // the expression is typed to return a reference type. | ||
| ?? (propertyExpression.Body as UnaryExpression)?.Operand as MemberExpression; | ||
|
|
||
| if ( | ||
| memberExpression?.Member is not PropertyInfo property | ||
| || !property.DeclaringType!.IsAssignableFrom(typeof(TOwner)) | ||
| ) | ||
| { | ||
| throw new ArgumentException( | ||
| "Provided expression must reference a property of the owner type.", | ||
| nameof(propertyExpression) | ||
| ); | ||
|
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.
|
||
|
|
||
| /// <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 | ||
| || !property.DeclaringType!.IsAssignableFrom(typeof(TOwner)) | ||
| ) | ||
| { | ||
| throw new ArgumentException( | ||
| "Provided expression must reference a property of the owner type.", | ||
| 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.
|
||
| } | ||
| } | ||
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.