feat: add join for list of Task<Result<T>>

Allow joining `IEnumerable<Task<Result<T>>>` to one single `Task<Result<IReadOnlyList<T>>>` contains the success value of each result.
This commit is contained in:
Louis Seubert 2024-05-01 17:48:11 +02:00
parent 16ef85906f
commit 1a8737ffa5
Signed by: louis9902
GPG key ID: 4B9DB28F826553BD

View file

@ -34,4 +34,54 @@ public static partial class Extensions
return list; return list;
} }
/// <inheritdoc cref="Join{T}(System.Collections.Generic.IEnumerable{Geekeey.Extensions.Result.Result{T}})"/>
/// <remarks>
/// For parallel execution of the async tasks, one should await the <c>Task.WhenAll()</c> of the provided list
/// before calling this function
/// </remarks>
/// <seealso cref="Join{T}(System.Collections.Generic.IEnumerable{Geekeey.Extensions.Result.Result{T}})"/>
// ReSharper disable once InconsistentNaming
public static async Task<Result<IReadOnlyList<T>>> Join<T>(this IEnumerable<Task<Result<T>>> results)
{
_ = results.TryGetNonEnumeratedCount(out var count);
var list = new List<T>(count);
foreach (var result in results)
{
if (!(await result).TryGetValue(out var value, out var error))
{
return new Result<IReadOnlyList<T>>(error);
}
list.Add(value);
}
return list;
}
/// <inheritdoc cref="Join{T}(System.Collections.Generic.IEnumerable{Geekeey.Extensions.Result.Result{T}})"/>
/// <remarks>
/// For parallel execution of the async tasks, one should await the <c>Task.WhenAll()</c> of the provided list
/// before calling this function
/// </remarks>
/// <seealso cref="Join{T}(System.Collections.Generic.IEnumerable{Geekeey.Extensions.Result.Result{T}})"/>
// ReSharper disable once InconsistentNaming
public static async ValueTask<Result<IReadOnlyList<T>>> Join<T>(this IEnumerable<ValueTask<Result<T>>> results)
{
_ = results.TryGetNonEnumeratedCount(out var count);
var list = new List<T>(count);
foreach (var result in results)
{
if (!(await result).TryGetValue(out var value, out var error))
{
return new Result<IReadOnlyList<T>>(error);
}
list.Add(value);
}
return list;
}
} }