Simplify iteration logic in ForEachT.cs

Removed the ItemSource property and related logic in ForEachT.cs. Instead of considering two sources (Items and ItemSource) for iterations, the code now only iterates over the Items collection. Additional logic has been added to initialize Items to an empty collection when it is not set.
This commit is contained in:
Sipke Schoorstra 2024-01-26 21:21:21 +01:00
parent 396e84c805
commit b933def16d

View file

@ -47,13 +47,7 @@ public class ForEach<T> : Activity
/// The set of values to iterate.
/// </summary>
[Input(Description = "The set of values to iterate.")]
public Input<ICollection<T>>? Items { get; set; }
/// <summary>
/// The source of values to iterate.
/// </summary>
[Input(Description = "The set of values to iterate.")]
public Input<IAsyncEnumerable<T>>? ItemSource { get; set; }
public Input<ICollection<T>> Items { get; set; } = new(Array.Empty<T>());
/// <summary>
/// The activity to execute for each iteration.
@ -85,16 +79,15 @@ public class ForEach<T> : Activity
}
var currentIndex = context.GetProperty<int>(CurrentIndexProperty);
var currentValueTuple = await GetCurrentValueAsync(context, currentIndex);
var items = context.Get(Items)!.ToList();
if (!currentValueTuple.Exists)
if (currentIndex >= items.Count)
{
await context.CompleteActivityAsync();
return;
}
var currentValue = currentValueTuple.Value;
var currentValue = items[currentIndex];
context.Set(CurrentValue, currentValue);
if (Body != null)
@ -113,36 +106,6 @@ public class ForEach<T> : Activity
context.UpdateProperty<int>(CurrentIndexProperty, x => x + 1);
}
private async Task<(T Value, bool Exists)> GetCurrentValueAsync(ActivityExecutionContext context, int currentIndex)
{
var items = context.Get(Items)?.ToList();
if (items != null)
{
return (currentIndex >= items.Count ? (default, false) : (items[currentIndex], true))!;
}
var itemSource = context.Get(ItemSource);
if(itemSource != null)
{
await using var enumerator = itemSource.GetAsyncEnumerator();
// Move the cursor to the current index.
for (var i = 0; i < currentIndex; i++)
await enumerator.MoveNextAsync();
var hasNext = await enumerator.MoveNextAsync();
if(!hasNext)
return (default, false)!;
return (enumerator.Current, true);
}
return (default, false)!;
}
private async ValueTask OnChildCompleted(ActivityCompletedContext context)
{
await HandleIteration(context.TargetContext);