Skip to content

Commit

Permalink
Use async iterators for Cast.
Browse files Browse the repository at this point in the history
  • Loading branch information
bartdesmet committed Feb 19, 2019
1 parent ccc5d2b commit 490e2dd
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Ix.NET/Source/System.Linq.Async/System/Linq/Operators/Cast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace System.Linq
{
public static partial class AsyncEnumerable
{
// NB: This is a non-standard LINQ operator, because we don't have a non-generic IAsyncEnumerable.
// We're keeping it to enable `from T x in xs` binding in C#.

public static IAsyncEnumerable<TResult> Cast<TResult>(this IAsyncEnumerable<object> source)
{
if (source == null)
Expand All @@ -19,9 +23,22 @@ public static IAsyncEnumerable<TResult> Cast<TResult>(this IAsyncEnumerable<obje
return typedSource;
}

#if USE_ASYNC_ITERATOR
return Create(Core);

async IAsyncEnumerator<TResult> Core(CancellationToken cancellationToken)
{
await foreach (var obj in AsyncEnumerableExtensions.WithCancellation(source, cancellationToken).ConfigureAwait(false))
{
yield return (TResult)obj;
}
}
#else
return new CastAsyncIterator<TResult>(source);
#endif
}

#if !USE_ASYNC_ITERATOR
private sealed class CastAsyncIterator<TResult> : AsyncIterator<TResult>
{
private readonly IAsyncEnumerable<object> _source;
Expand Down Expand Up @@ -71,5 +88,6 @@ protected override async ValueTask<bool> MoveNextCore()
return false;
}
}
#endif
}
}

0 comments on commit 490e2dd

Please sign in to comment.