Skip to content

Bug fixes. #7

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 5 commits into from
May 4, 2023
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
27 changes: 14 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ A package that brings data-binding to your Unity project.
- [Property](#propertyt--readonlypropertyt)
- [Command](#command--commandt)
- [AsyncCommand](#asynccommand--asynccommandt)
- [AsyncLazyCommand](#asynclazycommand--asynclazycommandt)
- [PropertyValueConverter](#propertyvalueconvertertsourcetype-ttargettype)
- [ParameterValueConverter](#parametervalueconverterttargettype)
- [Quick start](#watch-quick-start)
Expand Down Expand Up @@ -198,7 +197,6 @@ The included types are:
- [Property\<T\> & ReadOnlyProperty\<T\>](#propertyt--readonlypropertyt)
- [Command & Command\<T\>](#command--commandt)
- [AsyncCommand & AsyncCommand\<T\>](#asynccommand--asynccommandt)
- [AsyncLazyCommand & AsyncLazyCommand\<T\>](#asynclazycommand--asynclazycommandt)
- [PropertyValueConverter\<TSourceType, TTargetType\>](#propertyvalueconvertertsourcetype-ttargettype)
- [ParameterValueConverter\<TTargetType\>](#parametervalueconverterttargettype)
- [IProperty\<T\> & IReadOnlyProperty\<T\>](#propertyt--readonlypropertyt)
Expand Down Expand Up @@ -425,6 +423,18 @@ public class ImageViewerViewModel : IBindingContext
}
```

To allow the same async command to be invoked concurrently multiple times, set the `AllowConcurrency` property of the `AsyncCommand` to `true`.

```csharp
public class MainViewModel : IBindingContext
{
public MainViewModel()
{
RunConcurrentlyCommand = new AsyncCommand(RunConcurrentlyAsync) { AllowConcurrency = true };
}
}
```

If you want to create an async command that supports cancellation, use the `WithCancellation` extension method.

```csharp
Expand All @@ -446,22 +456,13 @@ public class MyViewModel : IBindingContext

private void Cancel()
{
// If the underlying command is not running, or
// if it does not support cancellation, this method will perform no action.
// If the underlying command is not running, this method will perform no action.
MyAsyncCommand.Cancel();
}
}
```

If the command supports cancellation, previous invocations will automatically be canceled if a new one is started.

> **Note:** You need to import the [UniTask](https://github.com/Cysharp/UniTask) package in order to use async commands.

### AsyncLazyCommand & AsyncLazyCommand\<T\>

The `AsyncLazyCommand` and `AsyncLazyCommand<T>` are have the same functionality as the `AsyncCommand`'s, except they prevent the same async command from being invoked concurrently multiple times.

Let's imagine a scenario similar to the one described in the `AsyncCommand` sample, but a user clicks the `Download Image` button several times while the async operation is running. In this case, `AsyncLazyCommand` will ignore all clicks until previous async operation has completed.
If a command supports cancellation and the `AllowConcurrency` property is set to `true`, all running commands will be canceled.

> **Note:** You need to import the [UniTask](https://github.com/Cysharp/UniTask) package in order to use async commands.

Expand Down
77 changes: 43 additions & 34 deletions src/UnityMvvmToolkit.Core/Internal/BindingContextMemberProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,40 +63,49 @@ private static bool TryGetFieldHashCode(Type contextType, FieldInfo fieldInfo, o
return TryGetHashCode(contextType, fieldInfo.Name, fieldInfo.FieldType, out hashCode);
}

if (TryGetPropertyNameFromAttribute(fieldInfo, out var fieldName))
if (HasObservableAttribute(fieldInfo, out var propertyName) == false)
{
return TryGetHashCode(contextType, fieldName, fieldInfo.FieldType, out hashCode);
hashCode = default;
return false;
}

fieldName = fieldInfo.Name;
return string.IsNullOrWhiteSpace(propertyName)
? TryGetHashCode(contextType, GetFieldName(fieldInfo.Name), fieldInfo.FieldType, out hashCode)
: TryGetHashCode(contextType, propertyName, fieldInfo.FieldType, out hashCode);
}

if (fieldName.Length > 1)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetPropertyHashCode(Type contextType, PropertyInfo propertyInfo, out int hashCode)
{
if (propertyInfo.GetMethod.IsPrivate)
{
if (fieldName[0] == '_')
{
fieldName = fieldName[1..]; // TODO: Get rid of allocation.
}

if (fieldName[0] == 'm' && fieldName[1] == '_')
{
fieldName = fieldName[2..]; // TODO: Get rid of allocation.
}
hashCode = default;
return false;
}

if (string.IsNullOrEmpty(fieldName))
return TryGetHashCode(contextType, propertyInfo.Name, propertyInfo.PropertyType, out hashCode);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetHashCode(Type contextType, string memberName, Type memberType, out int hashCode)
{
if (typeof(IBaseCommand).IsAssignableFrom(memberType) ||
typeof(IBaseProperty).IsAssignableFrom(memberType))
{
throw new InvalidOperationException($"Field name '{fieldName}' is not supported.");
hashCode = HashCodeHelper.GetMemberHashCode(contextType, memberName);
return true;
}

return TryGetHashCode(contextType, fieldName, fieldInfo.FieldType, out hashCode);
hashCode = default;
return false;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetPropertyNameFromAttribute(MemberInfo fieldInfo, out string propertyName)
private static bool HasObservableAttribute(MemberInfo fieldInfo, out string propertyName)
{
var observableAttribute = fieldInfo.GetCustomAttribute<ObservableAttribute>();

if (observableAttribute == null || string.IsNullOrWhiteSpace(observableAttribute.PropertyName))
if (observableAttribute == null)
{
propertyName = default;
return false;
Expand All @@ -107,29 +116,29 @@ private static bool TryGetPropertyNameFromAttribute(MemberInfo fieldInfo, out st
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetPropertyHashCode(Type contextType, PropertyInfo propertyInfo, out int hashCode)
private static string GetFieldName(string fieldName)
{
if (propertyInfo.GetMethod.IsPrivate)
var resultName = fieldName;

if (resultName.Length > 1)
{
hashCode = default;
return false;
}
if (resultName[0] == '_')
{
resultName = resultName[1..]; // TODO: Get rid of allocation.
}

return TryGetHashCode(contextType, propertyInfo.Name, propertyInfo.PropertyType, out hashCode);
}
if (resultName[0] == 'm' && resultName[1] == '_')
{
resultName = resultName[2..]; // TODO: Get rid of allocation.
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetHashCode(Type contextType, string memberName, Type memberType, out int hashCode)
{
if (typeof(IBaseCommand).IsAssignableFrom(memberType) ||
typeof(IBaseProperty).IsAssignableFrom(memberType))
if (string.IsNullOrEmpty(resultName))
{
hashCode = HashCodeHelper.GetMemberHashCode(contextType, memberName);
return true;
throw new InvalidOperationException($"Field name '{resultName}' is not supported.");
}

hashCode = default;
return false;
return resultName;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,40 +63,49 @@ private static bool TryGetFieldHashCode(Type contextType, FieldInfo fieldInfo, o
return TryGetHashCode(contextType, fieldInfo.Name, fieldInfo.FieldType, out hashCode);
}

if (TryGetPropertyNameFromAttribute(fieldInfo, out var fieldName))
if (HasObservableAttribute(fieldInfo, out var propertyName) == false)
{
return TryGetHashCode(contextType, fieldName, fieldInfo.FieldType, out hashCode);
hashCode = default;
return false;
}

fieldName = fieldInfo.Name;
return string.IsNullOrWhiteSpace(propertyName)
? TryGetHashCode(contextType, GetFieldName(fieldInfo.Name), fieldInfo.FieldType, out hashCode)
: TryGetHashCode(contextType, propertyName, fieldInfo.FieldType, out hashCode);
}

if (fieldName.Length > 1)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetPropertyHashCode(Type contextType, PropertyInfo propertyInfo, out int hashCode)
{
if (propertyInfo.GetMethod.IsPrivate)
{
if (fieldName[0] == '_')
{
fieldName = fieldName[1..]; // TODO: Get rid of allocation.
}

if (fieldName[0] == 'm' && fieldName[1] == '_')
{
fieldName = fieldName[2..]; // TODO: Get rid of allocation.
}
hashCode = default;
return false;
}

if (string.IsNullOrEmpty(fieldName))
return TryGetHashCode(contextType, propertyInfo.Name, propertyInfo.PropertyType, out hashCode);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetHashCode(Type contextType, string memberName, Type memberType, out int hashCode)
{
if (typeof(IBaseCommand).IsAssignableFrom(memberType) ||
typeof(IBaseProperty).IsAssignableFrom(memberType))
{
throw new InvalidOperationException($"Field name '{fieldName}' is not supported.");
hashCode = HashCodeHelper.GetMemberHashCode(contextType, memberName);
return true;
}

return TryGetHashCode(contextType, fieldName, fieldInfo.FieldType, out hashCode);
hashCode = default;
return false;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetPropertyNameFromAttribute(MemberInfo fieldInfo, out string propertyName)
private static bool HasObservableAttribute(MemberInfo fieldInfo, out string propertyName)
{
var observableAttribute = fieldInfo.GetCustomAttribute<ObservableAttribute>();

if (observableAttribute == null || string.IsNullOrWhiteSpace(observableAttribute.PropertyName))
if (observableAttribute == null)
{
propertyName = default;
return false;
Expand All @@ -107,29 +116,29 @@ private static bool TryGetPropertyNameFromAttribute(MemberInfo fieldInfo, out st
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetPropertyHashCode(Type contextType, PropertyInfo propertyInfo, out int hashCode)
private static string GetFieldName(string fieldName)
{
if (propertyInfo.GetMethod.IsPrivate)
var resultName = fieldName;

if (resultName.Length > 1)
{
hashCode = default;
return false;
}
if (resultName[0] == '_')
{
resultName = resultName[1..]; // TODO: Get rid of allocation.
}

return TryGetHashCode(contextType, propertyInfo.Name, propertyInfo.PropertyType, out hashCode);
}
if (resultName[0] == 'm' && resultName[1] == '_')
{
resultName = resultName[2..]; // TODO: Get rid of allocation.
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool TryGetHashCode(Type contextType, string memberName, Type memberType, out int hashCode)
{
if (typeof(IBaseCommand).IsAssignableFrom(memberType) ||
typeof(IBaseProperty).IsAssignableFrom(memberType))
if (string.IsNullOrEmpty(resultName))
{
hashCode = HashCodeHelper.GetMemberHashCode(contextType, memberName);
return true;
throw new InvalidOperationException($"Field name '{resultName}' is not supported.");
}

hashCode = default;
return false;
return resultName;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,25 @@ public AsyncCommand(Func<T, CancellationToken, UniTask> action, Func<bool> canEx

public void Execute(T parameter)
{
if (IsCommandRunning && AllowConcurrency == false)
{
return;
}

ExecuteAsync(parameter).Forget();
}

public async UniTask ExecuteAsync(T parameter, CancellationToken cancellationToken = default)
{
try
{
IsRunning = true;
SetCommandRunning(true);

await _action(parameter, cancellationToken);
}
finally
{
IsRunning = false;
SetCommandRunning(false);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,25 @@ public AsyncCommand(Func<CancellationToken, UniTask> action, Func<bool> canExecu

public void Execute()
{
if (IsCommandRunning && AllowConcurrency == false)
{
return;
}

ExecuteAsync().Forget();
}

public async UniTask ExecuteAsync(CancellationToken cancellationToken = default)
{
try
{
IsRunning = true;
SetCommandRunning(true);

await _action(cancellationToken);
}
finally
{
IsRunning = false;
SetCommandRunning(false);
}
}
}
Expand Down

This file was deleted.

This file was deleted.

Loading