Skip to content

Commit

Permalink
feat: add AsyncEnumerableFactory.FromSingleItem<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkallesen committed Aug 15, 2024
1 parent 06f05d0 commit 616fdce
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Atc/Factories/AsyncEnumerableFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,16 @@ public static async IAsyncEnumerable<T> Empty<T>()
await Task.CompletedTask;
yield break;
}

/// <summary>
/// Converts a single item into an <see cref="IAsyncEnumerable{T}"/>.
/// </summary>
/// <typeparam name="T">The type of the item.</typeparam>
/// <param name="item">The item to convert.</param>
/// <returns>An <see cref="IAsyncEnumerable{T}"/> containing the single item.</returns>
public static async IAsyncEnumerable<T> FromSingleItem<T>(T item)
{
yield return item;
await Task.CompletedTask;
}
}
63 changes: 63 additions & 0 deletions test/Atc.Tests/Factories/AsyncEnumerableFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,67 @@ public async Task Empty_ReturnsEmptySequence_WithDifferentTypes()
Assert.Empty(stringResult);
Assert.Empty(customTypeResult);
}

[Fact]
public async Task FromSingleItem_ReturnsAsyncEnumerableWithSingleItem()
{
// Arrange
const int item = 42;

// Act
var result = new List<int>();
await foreach (var value in AsyncEnumerableFactory.FromSingleItem(item))
{
result.Add(value);
}

// Assert
Assert.Single(result);
Assert.Equal(item, result.First());
}

[Fact]
public async Task FromSingleItem_ReturnsAsyncEnumerable_WithReferenceType()
{
// Arrange
const string item = "TestString";

// Act
var result = new List<string>();
await foreach (var value in AsyncEnumerableFactory.FromSingleItem(item))
{
result.Add(value);
}

// Assert
Assert.Single(result);
Assert.Equal(item, result.First());
}

[Fact]
public async Task FromSingleItem_CanBeEnumeratedMultipleTimes()
{
// Arrange
var item = 42;
var asyncEnumerable = AsyncEnumerableFactory.FromSingleItem(item);

// Act
var firstEnumeration = new List<int>();
await foreach (var value in asyncEnumerable)
{
firstEnumeration.Add(value);
}

var secondEnumeration = new List<int>();
await foreach (var value in asyncEnumerable)
{
secondEnumeration.Add(value);
}

// Assert
Assert.Single(firstEnumeration);
Assert.Single(secondEnumeration);
Assert.Equal(item, firstEnumeration.First());
Assert.Equal(item, secondEnumeration.First());
}
}

0 comments on commit 616fdce

Please sign in to comment.